Skip to content

Commit

Permalink
perf(tag): memoize
Browse files Browse the repository at this point in the history
  • Loading branch information
SukkaW committed Oct 2, 2021
1 parent 5a35462 commit c570ef7
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 6 deletions.
24 changes: 24 additions & 0 deletions lib/plugins/tag/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
'use strict';

const { default: moize } = require('moize');

module.exports = ctx => {
const { tag } = ctx.extend;

Expand Down Expand Up @@ -52,3 +54,25 @@ module.exports = ctx => {

tag.register('youtube', require('./youtube'));
};

// Use WeakMap to track different ctx (in case there is any)
const moized = new WeakMap();

module.exports.postFindOneFactory = function postFindOneFactory(ctx) {
if (moized.has(ctx)) {
return moized.get(ctx);
}

const moizedPostFindOne = moize(createPostFindOne(ctx), {
isDeepEqual: true,
maxSize: 20
});
moized.set(ctx, moizedPostFindOne);

return moizedPostFindOne;
};

function createPostFindOne(ctx) {
const Post = ctx.model('Post');
return Post.findOne.bind(Post);
}
5 changes: 2 additions & 3 deletions lib/plugins/tag/post_link.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

const { encodeURL, escapeHTML } = require('hexo-util');
const { resolve } = require('url');
const { postFindOneFactory } = require('./');

/**
* Post link tag
Expand All @@ -10,8 +11,6 @@ const { resolve } = require('url');
* {% post_link slug [title] [escape] %}
*/
module.exports = ctx => {
const Post = ctx.model('Post');

return function postLinkTag(args) {
const error = `<a href="#">Post not found: ${args.join(' ') || 'Invalid post_link'}</a>`;
const slug = args.shift();
Expand All @@ -24,7 +23,7 @@ module.exports = ctx => {
escape = 'true';
}

const post = Post.findOne({slug});
const post = postFindOneFactory(ctx)({ slug });
if (!post) return error;

let title = args.length ? args.join(' ') : post.title;
Expand Down
5 changes: 2 additions & 3 deletions lib/plugins/tag/post_path.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

const { resolve } = require('url');
const { encodeURL } = require('hexo-util');
const { postFindOneFactory } = require('./');

/**
* Post path tag
Expand All @@ -10,13 +11,11 @@ const { encodeURL } = require('hexo-util');
* {% post_path slug %}
*/
module.exports = ctx => {
const Post = ctx.model('Post');

return function postPathTag(args) {
const slug = args.shift();
if (!slug) return;

const post = Post.findOne({slug});
const post = postFindOneFactory(ctx)({ slug });
if (!post) return;

const link = encodeURL(resolve(ctx.config.root, post.path));
Expand Down

0 comments on commit c570ef7

Please sign in to comment.