Skip to content

Commit

Permalink
perf(postAsset): utilise PostAsset.findById()
Browse files Browse the repository at this point in the history
  • Loading branch information
curbengh committed Aug 18, 2020
1 parent fc9ef72 commit 551eaae
Showing 1 changed file with 11 additions and 11 deletions.
22 changes: 11 additions & 11 deletions lib/renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
const marked = require('marked');
const { encodeURL, slugize, stripHTML, url_for, isExternalLink } = require('hexo-util');
const MarkedRenderer = marked.Renderer;
const { sep } = require('path');

const anchorId = (str, transformOption) => {
return slugize(str.trim(), {transform: transformOption});
Expand Down Expand Up @@ -91,14 +90,15 @@ class Renderer extends MarkedRenderer {
image(href, title, text) {
const { hexo, options } = this;
const { relative_link } = hexo.config;
const { lazyload, prependRoot, postId } = options;
const { lazyload, prependRoot, postPath } = options;

if (!/^(#|\/\/|http(s)?:)/.test(href) && !relative_link && prependRoot) {
if (!/^(\/|\\)/.test(href) && postId) {
if (!href.startsWith('/') && !href.startsWith('\\') && postPath) {
const PostAsset = hexo.model('PostAsset');
// slug requires platform-specific path
const asset = PostAsset.findOne({ post: postId, slug: href.replace(/\/|\\/g, sep) });
if (asset) href = encodeURL(('/' + asset.path).replace(/\\/g, '/').replace(/\/{2,}/g, '/'));
// findById requires forward slash
const asset = PostAsset.findById(postPath + href.replace(/\\/g, '/'));
// asset.path is backward slash in Windows
if (asset) href = asset.path.replace(/\\/g, '/');
}
href = url_for.call(hexo, href);
}
Expand All @@ -118,24 +118,24 @@ marked.setOptions({
});

module.exports = function(data, options) {
const { post_asset_folder, marked: markedCfg } = this.config;
const { post_asset_folder, marked: markedCfg, source_dir } = this.config;
const { prependRoot, postAsset } = markedCfg;
const { path, text } = data;

// exec filter to extend renderer.
const renderer = new Renderer(this);
this.execFilterSync('marked:renderer', renderer, {context: this});

let postId = '';
let postPath = '';
if (path && post_asset_folder && prependRoot && postAsset) {
const Post = this.model('Post');
// Windows compatibility, Post.findOne() requires forward slash
const source = path.replace(this.source_dir, '').replace('\\', '/');
const source = path.substring(this.source_dir.length).replace(/\\/g, '/');
const post = Post.findOne({ source });
postId = post ? post._id : '';
postPath = post ? source_dir + '/_posts/' + post.slug + '/' : '';
}

return marked(text, Object.assign({
renderer
}, markedCfg, options, { postId }));
}, markedCfg, options, { postPath }));
};

0 comments on commit 551eaae

Please sign in to comment.