File tree Expand file tree Collapse file tree 2 files changed +43
-0
lines changed Expand file tree Collapse file tree 2 files changed +43
-0
lines changed Original file line number Diff line number Diff line change @@ -178,6 +178,12 @@ export class PostController {
178
178
return await this . redis . del ( "posts-index" ) ;
179
179
}
180
180
181
+ @Get ( "/search" )
182
+ @ApiOperation ( { summary : "搜索文章" } )
183
+ async search ( @Query ( "key" ) key : string ) {
184
+ return await this . postService . search ( key ) ;
185
+ }
186
+
181
187
@Get ( "/_like" )
182
188
async thumbsUpArticle (
183
189
@Query ( ) query : MongoIdDto ,
Original file line number Diff line number Diff line change @@ -274,6 +274,9 @@ export class PostService {
274
274
return ( await this . postModel . countDocuments ( { slug } ) ) === 0 ;
275
275
}
276
276
277
+ /**
278
+ * 创建文章索引
279
+ */
277
280
async createIndex ( ) {
278
281
// 1. 获取全部文章( 仅获取 Text, Title, Summary 字段 )
279
282
const posts = await this . model . find ( {
@@ -300,6 +303,40 @@ export class PostService {
300
303
} ) ;
301
304
}
302
305
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
+
303
340
async CreateDefaultPost ( cateId : string ) {
304
341
await this . postModel . countDocuments ( { } ) . then ( async ( count ) => {
305
342
if ( ! count ) {
You can’t perform that action at this time.
0 commit comments