Skip to content

Commit cc8c520

Browse files
authored
perf(processor/post): improve processing speed when config.post_asset_folder is enabled (#5473)
1 parent 093dc2d commit cc8c520

File tree

1 file changed

+24
-11
lines changed

1 file changed

+24
-11
lines changed

lib/plugins/processor/post.ts

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
import { toDate, timezone, isExcludedFile, isTmpFile, isHiddenFile, isMatch } from './common';
22
import Promise from 'bluebird';
33
import { parse as yfm } from 'hexo-front-matter';
4-
import { extname, join } from 'path';
4+
import { extname, join, posix, sep } from 'path';
55
import { stat, listDir } from 'hexo-fs';
66
import { slugize, Pattern, Permalink } from 'hexo-util';
77
import { magenta } from 'picocolors';
88
import type { _File } from '../../box';
99
import type Hexo from '../../hexo';
1010
import type { Stats } from 'fs';
11+
import { PostSchema } from '../../types';
1112

1213
const postDir = '_posts/';
1314
const draftDir = '_drafts/';
@@ -268,29 +269,41 @@ function processAsset(ctx: Hexo, file: _File) {
268269
const PostAsset = ctx.model('PostAsset');
269270
const Post = ctx.model('Post');
270271
const id = file.source.substring(ctx.base_dir.length);
271-
const doc = PostAsset.findById(id);
272+
const postAsset = PostAsset.findById(id);
272273

273-
if (file.type === 'delete') {
274-
if (doc) {
275-
return doc.remove();
274+
if (file.type === 'delete' || Post.length === 0) {
275+
if (postAsset) {
276+
return postAsset.remove();
276277
}
277-
278278
return;
279279
}
280280

281-
// TODO: Better post searching
282-
const post = Post.toArray().find(post => file.source.startsWith(post.asset_dir));
283-
if (post != null && (post.published || ctx._showDrafts())) {
281+
const savePostAsset = (post: PostSchema) => {
284282
return PostAsset.save({
285283
_id: id,
286284
slug: file.source.substring(post.asset_dir.length),
287285
post: post._id,
288286
modified: file.type !== 'skip',
289287
renderable: file.params.renderable
290288
});
289+
};
290+
291+
if (postAsset) {
292+
// `postAsset.post` is `Post.id`.
293+
const post = Post.findById(postAsset.post);
294+
if (post != null && (post.published || ctx._showDrafts())) {
295+
return savePostAsset(post);
296+
}
297+
}
298+
299+
const assetDir = id.slice(0, id.lastIndexOf(sep));
300+
const post = Post.findOne(p => p.asset_dir.endsWith(posix.join(assetDir, '/')));
301+
if (post != null && (post.published || ctx._showDrafts())) {
302+
return savePostAsset(post);
291303
}
292304

293-
if (doc) {
294-
return doc.remove();
305+
// NOTE: Probably, unreachable.
306+
if (postAsset) {
307+
return postAsset.remove();
295308
}
296309
}

0 commit comments

Comments
 (0)