Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf(post): cache tags getter #5145

Merged
merged 2 commits into from
Oct 21, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions lib/models/post.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const moment = require('moment');
const { extname, join, sep } = require('path');
const Promise = require('bluebird');
const Moment = require('./types/moment');
const { full_url_for } = require('hexo-util');
const { full_url_for, Cache } = require('hexo-util');

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

const tagsGetterCache = new Cache();

module.exports = ctx => {
const Post = new Schema({
id: String,
Expand Down Expand Up @@ -63,12 +65,14 @@ module.exports = 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 @@ -82,6 +86,7 @@ module.exports = 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