list recent article

This commit is contained in:
aisensiy 2017-08-17 14:27:29 +08:00
parent 0c12253ef0
commit 0358fde252
11 changed files with 293 additions and 34 deletions

View File

@ -2,6 +2,7 @@ package io.spring.api;
import com.fasterxml.jackson.annotation.JsonRootName; import com.fasterxml.jackson.annotation.JsonRootName;
import io.spring.api.exception.InvalidRequestException; import io.spring.api.exception.InvalidRequestException;
import io.spring.application.Page;
import io.spring.application.article.ArticleQueryService; import io.spring.application.article.ArticleQueryService;
import io.spring.core.article.Article; import io.spring.core.article.Article;
import io.spring.core.article.ArticleRepository; import io.spring.core.article.ArticleRepository;
@ -13,9 +14,11 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.BindingResult; import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid; import javax.validation.Valid;
@ -52,6 +55,15 @@ public class ArticlesApi {
put("article", articleQueryService.findById(article.getId(), user).get()); put("article", articleQueryService.findById(article.getId(), user).get());
}}); }});
} }
@GetMapping
public ResponseEntity getArticles(@RequestParam(value = "offset", defaultValue = "0") int offset,
@RequestParam(value = "limit", defaultValue = "20") int limit,
@RequestParam(value = "tag", required = false) String tag,
@RequestParam(value = "favorited", required = false) String favoritedBy,
@RequestParam(value = "author", required = false) String author) {
return ResponseEntity.ok(articleQueryService.findRecentArticles(tag, author, favoritedBy, new Page(offset, limit)));
}
} }
@Getter @Getter

View File

@ -0,0 +1,33 @@
package io.spring.application;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Data
@Getter
@NoArgsConstructor
public class Page {
private static final int MAX_LIMIT = 100;
private int offset = 0;
private int limit = 20;
public Page(int offset, int limit) {
setOffset(offset);
setLimit(limit);
}
private void setOffset(int offset) {
if (offset > 0) {
this.offset = offset;
}
}
private void setLimit(int limit) {
if (limit > MAX_LIMIT) {
this.limit = MAX_LIMIT;
} else if (limit > 0) {
this.limit = limit;
}
}
}

View File

@ -0,0 +1,20 @@
package io.spring.application.article;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import java.util.List;
@Getter
public class ArticleDataList {
@JsonProperty("articles")
private final List<ArticleData> articleDatas;
@JsonProperty("articlesCount")
private final int count;
public ArticleDataList(List<ArticleData> articleDatas, int count) {
this.articleDatas = articleDatas;
this.count = count;
}
}

View File

@ -1,10 +1,13 @@
package io.spring.application.article; package io.spring.application.article;
import io.spring.application.Page;
import io.spring.application.profile.UserRelationshipQueryService; import io.spring.application.profile.UserRelationshipQueryService;
import io.spring.core.user.User; import io.spring.core.user.User;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional; import java.util.Optional;
@Service @Service
@ -54,4 +57,12 @@ public class ArticleQueryService {
user.getId(), user.getId(),
articleData.getProfileData().getId())); articleData.getProfileData().getId()));
} }
public ArticleDataList findRecentArticles(String tag, String author, String favoritedBy, Page page) {
List<String> articleIds = articleReadService.queryArticles(tag, author, favoritedBy, page);
int articleCount = articleReadService.countArticle(tag, author, favoritedBy);
return new ArticleDataList(
articleIds.size() == 0 ? new ArrayList<>() : articleReadService.findArticles(articleIds),
articleCount);
}
} }

View File

@ -1,13 +1,22 @@
package io.spring.application.article; package io.spring.application.article;
import io.spring.application.Page;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.List;
@Component @Component
@Mapper @Mapper
public interface ArticleReadService { public interface ArticleReadService {
ArticleData findById(@Param("id") String id); ArticleData findById(@Param("id") String id);
ArticleData findBySlug(@Param("slug") String slug); ArticleData findBySlug(@Param("slug") String slug);
List<String> queryArticles(@Param("tag") String tag, @Param("author") String author, @Param("favoritedBy") String favoritedBy, @Param("page") Page page);
int countArticle(@Param("tag") String tag, @Param("author") String author, @Param("favoritedBy") String favoritedBy);
List<ArticleData> findArticles(@Param("articleIds") List<String> articleIds);
} }

View File

@ -27,6 +27,10 @@ public class Article {
private DateTime updatedAt; private DateTime updatedAt;
public Article(String title, String description, String body, String[] tagList, String userId) { public Article(String title, String description, String body, String[] tagList, String userId) {
this(title, description, body, tagList, userId, new DateTime());
}
public Article(String title, String description, String body, String[] tagList, String userId, DateTime createdAt) {
this.id = UUID.randomUUID().toString(); this.id = UUID.randomUUID().toString();
this.slug = toSlug(title); this.slug = toSlug(title);
this.title = title; this.title = title;
@ -34,8 +38,8 @@ public class Article {
this.body = body; this.body = body;
this.tags = Arrays.stream(tagList).collect(toSet()).stream().map(Tag::new).collect(toList()); this.tags = Arrays.stream(tagList).collect(toSet()).stream().map(Tag::new).collect(toList());
this.userId = userId; this.userId = userId;
this.createdAt = new DateTime(); this.createdAt = createdAt;
this.updatedAt = new DateTime(); this.updatedAt = createdAt;
} }
public void update(String title, String description, String body) { public void update(String title, String description, String body) {

View File

@ -33,6 +33,59 @@
<include refid="selectArticleData"/> <include refid="selectArticleData"/>
where A.slug = #{slug} where A.slug = #{slug}
</select> </select>
<select id="queryArticles" resultMap="articleId">
select
DISTINCT(A.id) articleId, A.created_at
from
articles A
left join article_tags AT on A.id = AT.article_id
left join tags T on T.id = AT.tag_id
left join article_favorites AF on AF.article_id = A.id
<where>
<if test="tag != null">
T.name = #{tag}
</if>
<if test="author != null">
AND A.user_id = #{author}
</if>
<if test="favoritedBy != null">
AND AF.user_id = #{favoritedBy}
</if>
</where>
order by A.created_at desc
limit #{page.offset}, #{page.limit}
</select>
<select id="countArticle" resultType="java.lang.Integer">
select
count(DISTINCT A.id)
from
articles A
left join article_tags AT on A.id = AT.article_id
left join tags T on T.id = AT.tag_id
left join article_favorites AF on AF.article_id = A.id
<where>
<if test="tag != null">
T.name = #{tag}
</if>
<if test="author != null">
AND A.user_id = #{author}
</if>
<if test="favoritedBy != null">
AND AF.user_id = #{favoritedBy}
</if>
</where>
</select>
<select id="findArticles" resultMap="articleData">
<include refid="selectArticleData"/>
where A.id in
<foreach index="index" collection="articleIds" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</select>
<resultMap id="articleId" type="string">
<id javaType="string" column="articleId"/>
</resultMap>
<resultMap id="articleData" type="io.spring.application.article.ArticleData"> <resultMap id="articleData" type="io.spring.application.article.ArticleData">
<id column="articleId" property="id"/> <id column="articleId" property="id"/>

View File

@ -0,0 +1,39 @@
package io.spring;
import io.spring.application.article.ArticleData;
import io.spring.application.profile.ProfileData;
import io.spring.core.article.Article;
import io.spring.core.user.User;
import org.joda.time.DateTime;
import java.util.ArrayList;
import java.util.Arrays;
public class TestHelper {
public static ArticleData articleDataFixture(String seed, User user) {
DateTime now = new DateTime();
return new ArticleData(
seed + "id",
"title-" + seed,
"title " + seed,
"desc " + seed,
"body " + seed, false, 0, now, now, new ArrayList<>(),
new ProfileData(user.getId(), user.getUsername(), user.getBio(), user.getImage(), false));
}
public static ArticleData getArticleDataFromArticleAndUser(Article article, User user) {
DateTime time = new DateTime();
return new ArticleData(
article.getId(),
article.getSlug(),
article.getTitle(),
article.getDescription(),
article.getBody(),
false,
0,
time,
time,
Arrays.asList("joda"),
new ProfileData(user.getId(), user.getUsername(), user.getBio(), user.getImage(), false));
}
}

View File

@ -1,6 +1,7 @@
package io.spring.api; package io.spring.api;
import io.restassured.RestAssured; import io.restassured.RestAssured;
import io.spring.TestHelper;
import io.spring.application.article.ArticleData; import io.spring.application.article.ArticleData;
import io.spring.application.article.ArticleQueryService; import io.spring.application.article.ArticleQueryService;
import io.spring.application.profile.ProfileData; import io.spring.application.profile.ProfileData;
@ -42,17 +43,9 @@ public class ArticlesApiTest extends TestWithCurrentUser {
@MockBean @MockBean
private ArticleQueryService articleQueryService; private ArticleQueryService articleQueryService;
protected String email;
protected String username;
protected String defaultAvatar;
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
RestAssured.port = port; RestAssured.port = port;
email = "john@jacob.com";
username = "johnjacob";
defaultAvatar = "https://static.productionready.io/images/smiley-cyrus.jpg";
userFixture();
} }
@Test @Test
@ -124,18 +117,7 @@ public class ArticlesApiTest extends TestWithCurrentUser {
Article article = new Article("Test New Article", "Desc", "Body", new String[]{"java", "spring", "jpg"}, user.getId()); Article article = new Article("Test New Article", "Desc", "Body", new String[]{"java", "spring", "jpg"}, user.getId());
DateTime time = new DateTime(); DateTime time = new DateTime();
ArticleData articleData = new ArticleData( ArticleData articleData = TestHelper.getArticleDataFromArticleAndUser(article, user);
article.getId(),
article.getSlug(),
article.getTitle(),
article.getDescription(),
article.getBody(),
false,
0,
time,
time,
Arrays.asList("joda"),
new ProfileData(user.getId(), user.getUsername(), user.getBio(), user.getImage(), false));
when(articleQueryService.findBySlug(eq(slug), eq(null))).thenReturn(Optional.of(articleData)); when(articleQueryService.findBySlug(eq(slug), eq(null))).thenReturn(Optional.of(articleData));
@ -168,18 +150,7 @@ public class ArticlesApiTest extends TestWithCurrentUser {
Article article = new Article(title, description, body, new String[]{"java", "spring", "jpg"}, user.getId()); Article article = new Article(title, description, body, new String[]{"java", "spring", "jpg"}, user.getId());
DateTime time = new DateTime(); DateTime time = new DateTime();
ArticleData articleData = new ArticleData( ArticleData articleData = TestHelper.getArticleDataFromArticleAndUser(article, user);
article.getId(),
article.getSlug(),
article.getTitle(),
article.getDescription(),
article.getBody(),
false,
0,
time,
time,
Arrays.asList("joda"),
new ProfileData(user.getId(), user.getUsername(), user.getBio(), user.getImage(), false));
when(articleRepository.findBySlug(eq(article.getSlug()))).thenReturn(Optional.of(article)); when(articleRepository.findBySlug(eq(article.getSlug()))).thenReturn(Optional.of(article));
when(articleQueryService.findBySlug(eq(article.getSlug()), eq(user))).thenReturn(Optional.of(articleData)); when(articleQueryService.findBySlug(eq(article.getSlug()), eq(user))).thenReturn(Optional.of(articleData));

View File

@ -0,0 +1,46 @@
package io.spring.api;
import io.restassured.RestAssured;
import io.spring.application.Page;
import io.spring.application.article.ArticleDataList;
import io.spring.application.article.ArticleQueryService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import static io.spring.TestHelper.articleDataFixture;
import static java.util.Arrays.asList;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
public class ListArticleApiTest extends TestWithCurrentUser {
@MockBean
private ArticleQueryService articleQueryService;
@LocalServerPort
private int port;
@Before
public void setUp() throws Exception {
RestAssured.port = port;
userFixture();
}
@Test
public void should_get_default_article_list() throws Exception {
ArticleDataList articleDataList = new ArticleDataList(
asList(articleDataFixture("1", user), articleDataFixture("2", user)), 2);
when(articleQueryService.findRecentArticles(eq(null), eq(null), eq(null), eq(new Page(0, 20)))).thenReturn(articleDataList);
RestAssured.when()
.get("/articles")
.prettyPeek()
.then()
.statusCode(200);
}
}

View File

@ -1,5 +1,6 @@
package io.spring.application.article; package io.spring.application.article;
import io.spring.application.Page;
import io.spring.core.article.Article; import io.spring.core.article.Article;
import io.spring.core.article.ArticleRepository; import io.spring.core.article.ArticleRepository;
import io.spring.core.favorite.ArticleFavorite; import io.spring.core.favorite.ArticleFavorite;
@ -9,6 +10,7 @@ import io.spring.core.user.UserRepository;
import io.spring.infrastructure.article.MyBatisArticleRepository; import io.spring.infrastructure.article.MyBatisArticleRepository;
import io.spring.infrastructure.favorite.MyBatisArticleFavoriteRepository; import io.spring.infrastructure.favorite.MyBatisArticleFavoriteRepository;
import io.spring.infrastructure.user.MyBatisUserRepository; import io.spring.infrastructure.user.MyBatisUserRepository;
import org.joda.time.DateTime;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -75,4 +77,63 @@ public class ArticleQueryServiceTest {
assertThat(articleData.getFavoritesCount(), is(1)); assertThat(articleData.getFavoritesCount(), is(1));
assertThat(articleData.isFavorited(), is(true)); assertThat(articleData.isFavorited(), is(true));
} }
@Test
public void should_get_default_article_list() throws Exception {
Article anotherArticle = new Article("new article", "desc", "body", new String[]{"test"}, user.getId(), new DateTime().minusHours(1));
articleRepository.save(anotherArticle);
ArticleDataList recentArticles = queryService.findRecentArticles(null, null, null, new Page());
assertThat(recentArticles.getCount(), is(2));
assertThat(recentArticles.getArticleDatas().size(), is(2));
assertThat(recentArticles.getArticleDatas().get(0).getId(), is(article.getId()));
ArticleDataList nodata = queryService.findRecentArticles(null, null, null, new Page(2, 10));
assertThat(nodata.getCount(), is(2));
assertThat(nodata.getArticleDatas().size(), is(0));
}
@Test
public void should_query_article_by_author() throws Exception {
User anotherUser = new User("other@email.com", "other", "123", "", "");
userRepository.save(anotherUser);
Article anotherArticle = new Article("new article", "desc", "body", new String[]{"test"}, anotherUser.getId());
articleRepository.save(anotherArticle);
ArticleDataList recentArticles = queryService.findRecentArticles(null, user.getId(), null, new Page());
assertThat(recentArticles.getArticleDatas().size(), is(1));
assertThat(recentArticles.getCount(), is(1));
}
@Test
public void should_query_article_by_favorite() throws Exception {
User anotherUser = new User("other@email.com", "other", "123", "", "");
userRepository.save(anotherUser);
Article anotherArticle = new Article("new article", "desc", "body", new String[]{"test"}, anotherUser.getId());
articleRepository.save(anotherArticle);
ArticleFavorite articleFavorite = new ArticleFavorite(article.getId(), anotherUser.getId());
articleFavoriteRepository.save(articleFavorite);
ArticleDataList recentArticles = queryService.findRecentArticles(null, null, anotherUser.getId(), new Page());
assertThat(recentArticles.getArticleDatas().size(), is(1));
assertThat(recentArticles.getCount(), is(1));
assertThat(recentArticles.getArticleDatas().get(0).getId(), is(article.getId()));
}
@Test
public void should_query_article_by_tag() throws Exception {
Article anotherArticle = new Article("new article", "desc", "body", new String[]{"test"}, user.getId());
articleRepository.save(anotherArticle);
ArticleDataList recentArticles = queryService.findRecentArticles("spring", null, null, new Page());
assertThat(recentArticles.getArticleDatas().size(), is(1));
assertThat(recentArticles.getCount(), is(1));
assertThat(recentArticles.getArticleDatas().get(0).getId(), is(article.getId()));
ArticleDataList notag = queryService.findRecentArticles("notag", null, null, new Page());
assertThat(notag.getCount(), is(0));
}
} }