Skip to content

Commit 89acf8c

Browse files
committed
feat(posts): search posts api
1 parent 243862c commit 89acf8c

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

src/modules/post/post.controller.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,12 @@ export class PostController {
178178
return await this.redis.del("posts-index");
179179
}
180180

181+
@Get("/search")
182+
@ApiOperation({ summary: "搜索文章" })
183+
async search(@Query("key") key: string) {
184+
return await this.postService.search(key);
185+
}
186+
181187
@Get("/_like")
182188
async thumbsUpArticle(
183189
@Query() query: MongoIdDto,

src/modules/post/post.service.ts

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,9 @@ export class PostService {
274274
return (await this.postModel.countDocuments({ slug })) === 0;
275275
}
276276

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

306+
/**
307+
* 搜索文章
308+
* @param keyword 关键词
309+
*/
310+
search(keyword: string) {
311+
return this.redis.get("posts-index").then((index: string) => {
312+
if (!index) {
313+
return this.createIndex().then(() => {
314+
return this.redis.get("posts-index");
315+
}).then((index: string) => {
316+
return this.search(keyword);
317+
}).catch(() => {
318+
return [];
319+
});
320+
}
321+
const indexJson = JSON.parse(index);
322+
const result = indexJson.filter((post) => {
323+
return post.text.includes(keyword) || post.title.includes(keyword);
324+
}).map((post) => {
325+
return {
326+
text: post.text,
327+
title: post.title,
328+
summary: post.summary,
329+
created: post.created,
330+
};
331+
}).sort((a, b) => {
332+
return b.created.getTime() - a.created.getTime();
333+
}).slice(0, 10);
334+
return result;
335+
}).catch(() => {
336+
return [];
337+
});
338+
}
339+
303340
async CreateDefaultPost(cateId: string) {
304341
await this.postModel.countDocuments({}).then(async (count) => {
305342
if (!count) {

0 commit comments

Comments
 (0)