@@ -17,6 +17,7 @@ import { CommentModel, CommentType } from "../comments/comments.model";
17
17
import { ImageService } from "~/processors/helper/helper.image.service" ;
18
18
import { PagerDto } from "~/shared/dto/pager.dto" ;
19
19
import { addYearCondition } from "~/transformers/db-query.transformer" ;
20
+ import { CacheService } from "~/processors/cache/cache.service" ;
20
21
21
22
@Injectable ( )
22
23
export class PostService {
@@ -29,6 +30,7 @@ export class PostService {
29
30
@Inject ( forwardRef ( ( ) => CategoryService ) )
30
31
private readonly categoryService : CategoryService ,
31
32
private readonly imageService : ImageService ,
33
+ private readonly redis : CacheService ,
32
34
) { }
33
35
get model ( ) {
34
36
return this . postModel ;
@@ -272,16 +274,30 @@ export class PostService {
272
274
return ( await this . postModel . countDocuments ( { slug } ) ) === 0 ;
273
275
}
274
276
275
- async createIndexed ( ) {
276
- return await this . model . createIndexes ( {
277
- background : true ,
278
- unique : true ,
279
- name : "post-indexes" ,
280
- default_language : "Chinese" ,
281
- partialFilterExpression : {
282
- hide : { $eq : false } , // 只创建不隐藏的文章
283
- } ,
284
- } )
277
+ async createIndex ( ) {
278
+ // 1. 获取全部文章( 仅获取 Text, Title, Summary 字段 )
279
+ const posts = await this . model . find ( {
280
+ hide : false ,
281
+ } , {
282
+ text : 1 ,
283
+ title : 1 ,
284
+ summary : 1 ,
285
+ created : 1 ,
286
+ } ) . sort ( { created : - 1 } ) . lean ( )
287
+ // 2. 将文章转换为 json 字符串
288
+ let postsJson : { text : string , title : string , summary ?: string , created ?: Date } [ ] = [ ] ;
289
+ for ( let post of posts ) {
290
+ postsJson . push ( {
291
+ text : post . text ,
292
+ title : post . title ,
293
+ summary : post . summary ,
294
+ created : post . created ,
295
+ } )
296
+ }
297
+ // 3. 创建索引,存入 Redis
298
+ return await this . redis . set ( "posts-index" , JSON . stringify ( postsJson ) , {
299
+ ttl : 24 * 60 * 60 , // 1 day
300
+ } ) ;
285
301
}
286
302
287
303
async CreateDefaultPost ( cateId : string ) {
0 commit comments