Skip to content

Commit 2790445

Browse files
committed
refactor: use Post.findById if postAsset exists
1 parent 9385c81 commit 2790445

File tree

1 file changed

+23
-12
lines changed

1 file changed

+23
-12
lines changed

lib/plugins/processor/post.ts

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ 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';
12+
import { sep } from 'path/posix';
1113

1214
const postDir = '_posts/';
1315
const draftDir = '_drafts/';
@@ -270,28 +272,37 @@ function processAsset(ctx: Hexo, file: _File) {
270272
const id = file.source.substring(ctx.base_dir.length);
271273
const doc = PostAsset.findById(id);
272274

273-
if (file.type === 'delete') {
275+
if (file.type === 'delete' || Post.length === 0) {
274276
if (doc) {
275277
return doc.remove();
276278
}
277-
278279
return;
279280
}
280281

281-
if (Post.length > 0) {
282-
const assetDir = id.slice(0, id.lastIndexOf('/'));
283-
const post = Post.findOne(p => p.asset_dir.endsWith(posix.join(assetDir, '/')));
282+
const savePostAsset = (post: PostSchema) => {
283+
return PostAsset.save({
284+
_id: id,
285+
slug: file.source.substring(post.asset_dir.length),
286+
post: post._id,
287+
modified: file.type !== 'skip',
288+
renderable: file.params.renderable
289+
});
290+
}
291+
292+
if (doc) {
293+
// `doc.post` is `Post.id`.
294+
const post = Post.findById(doc.post);
284295
if (post != null && (post.published || ctx._showDrafts())) {
285-
return PostAsset.save({
286-
_id: id,
287-
slug: file.source.substring(post.asset_dir.length),
288-
post: post._id,
289-
modified: file.type !== 'skip',
290-
renderable: file.params.renderable
291-
});
296+
return savePostAsset(post);
292297
}
293298
}
294299

300+
const assetDir = id.slice(0, id.lastIndexOf(sep));
301+
const post = Post.findOne(p => p.asset_dir.endsWith(posix.join(assetDir, '/')));
302+
if (post != null && (post.published || ctx._showDrafts())) {
303+
return savePostAsset(post);
304+
}
305+
295306
if (doc) {
296307
return doc.remove();
297308
}

0 commit comments

Comments
 (0)