Skip to content

Commit

Permalink
feat(posts): search posts api
Browse files Browse the repository at this point in the history
  • Loading branch information
wibus-wee committed Aug 21, 2022
1 parent 243862c commit 89acf8c
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/modules/post/post.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,12 @@ export class PostController {
return await this.redis.del("posts-index");
}

@Get("/search")
@ApiOperation({ summary: "搜索文章" })
async search(@Query("key") key: string) {
return await this.postService.search(key);
}

@Get("/_like")
async thumbsUpArticle(
@Query() query: MongoIdDto,
Expand Down
37 changes: 37 additions & 0 deletions src/modules/post/post.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,9 @@ export class PostService {
return (await this.postModel.countDocuments({ slug })) === 0;
}

/**
* 创建文章索引
*/
async createIndex() {
// 1. 获取全部文章( 仅获取 Text, Title, Summary 字段 )
const posts = await this.model.find({
Expand All @@ -300,6 +303,40 @@ export class PostService {
});
}

/**
* 搜索文章
* @param keyword 关键词
*/
search(keyword: string) {
return this.redis.get("posts-index").then((index: string) => {
if (!index) {
return this.createIndex().then(() => {
return this.redis.get("posts-index");
}).then((index: string) => {
return this.search(keyword);
}).catch(() => {
return [];
});
}
const indexJson = JSON.parse(index);
const result = indexJson.filter((post) => {
return post.text.includes(keyword) || post.title.includes(keyword);
}).map((post) => {
return {
text: post.text,
title: post.title,
summary: post.summary,
created: post.created,
};
}).sort((a, b) => {
return b.created.getTime() - a.created.getTime();
}).slice(0, 10);
return result;
}).catch(() => {
return [];
});
}

async CreateDefaultPost(cateId: string) {
await this.postModel.countDocuments({}).then(async (count) => {
if (!count) {
Expand Down

0 comments on commit 89acf8c

Please sign in to comment.