Skip to content

Commit b0adae8

Browse files
committed
feat(posts): create index to redis
1 parent 264494c commit b0adae8

File tree

1 file changed

+26
-10
lines changed

1 file changed

+26
-10
lines changed

src/modules/post/post.service.ts

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import { CommentModel, CommentType } from "../comments/comments.model";
1717
import { ImageService } from "~/processors/helper/helper.image.service";
1818
import { PagerDto } from "~/shared/dto/pager.dto";
1919
import { addYearCondition } from "~/transformers/db-query.transformer";
20+
import { CacheService } from "~/processors/cache/cache.service";
2021

2122
@Injectable()
2223
export class PostService {
@@ -29,6 +30,7 @@ export class PostService {
2930
@Inject(forwardRef(() => CategoryService))
3031
private readonly categoryService: CategoryService,
3132
private readonly imageService: ImageService,
33+
private readonly redis: CacheService,
3234
) {}
3335
get model() {
3436
return this.postModel;
@@ -272,16 +274,30 @@ export class PostService {
272274
return (await this.postModel.countDocuments({ slug })) === 0;
273275
}
274276

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+
});
285301
}
286302

287303
async CreateDefaultPost(cateId: string) {

0 commit comments

Comments
 (0)