Skip to content

Commit

Permalink
perf(post): cache tags getter (#5145)
Browse files Browse the repository at this point in the history
Co-authored-by: uiolee <[email protected]>
  • Loading branch information
SukkaW and uiolee authored Oct 21, 2023
1 parent 7b588e7 commit 3059fa0
Showing 1 changed file with 10 additions and 5 deletions.
15 changes: 10 additions & 5 deletions lib/models/post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import moment from 'moment';
import { extname, join, sep } from 'path';
import Promise from 'bluebird';
import Moment from './types/moment';
import { full_url_for } from 'hexo-util';
import { full_url_for, Cache } from 'hexo-util';

function pickID(data) {
return data._id;
Expand All @@ -13,6 +13,8 @@ function removeEmptyTag(tags) {
return tags.filter(tag => tag != null && tag !== '').map(tag => `${tag}`);
}

const tagsGetterCache = new Cache();

export = ctx => {
const Post = new warehouse.Schema({
id: String,
Expand Down Expand Up @@ -60,12 +62,14 @@ export = ctx => {
});

Post.virtual('tags').get(function() {
const PostTag = ctx.model('PostTag');
const Tag = ctx.model('Tag');
return tagsGetterCache.apply(this._id, () => {
const PostTag = ctx.model('PostTag');
const Tag = ctx.model('Tag');

const ids = PostTag.find({post_id: this._id}, {lean: true}).map(item => item.tag_id);
const ids = PostTag.find({post_id: this._id}, {lean: true}).map(item => item.tag_id);

return Tag.find({_id: {$in: ids}});
return Tag.find({_id: {$in: ids}});
});
});

Post.method('notPublished', function() {
Expand All @@ -79,6 +83,7 @@ export = ctx => {
// If the post is unpublished then the tag needs to be removed, thus the function cannot be returned early here
tags = [];
}
tagsGetterCache.flush();
tags = removeEmptyTag(tags);

const PostTag = ctx.model('PostTag');
Expand Down

0 comments on commit 3059fa0

Please sign in to comment.