-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget-posts-plugin.js
58 lines (53 loc) · 1.52 KB
/
get-posts-plugin.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import { join } from "path";
import { readdir, access, constants } from "fs/promises";
export default function getPostsPlugin() {
const virtualModuleId = "virtual:get-posts";
const resolvedVirtualModuleId = "\0" + virtualModuleId;
const postsDir = join(process.cwd(), "public", "_posts");
const postPath = (p) => join(postsDir, p, "index.md");
return {
name: "get-posts",
enforce: "pre",
resolveId(id) {
if (id === virtualModuleId) {
return resolvedVirtualModuleId;
}
},
async handleHotUpdate({ file, server }) {
const isPostUpdated = file.match(/\/_posts\/(.*)\/.*$/);
if (isPostUpdated) {
const name = isPostUpdated[1];
try {
await access(postPath(name), constants.R_OK);
server.ws.send({
type: "custom",
event: "post-update",
data: {
file,
name,
},
});
} catch {}
}
return [];
},
async load(id) {
if (id === resolvedVirtualModuleId) {
let rawPosts = await readdir(postsDir, { withFileTypes: true });
rawPosts = rawPosts.filter((dirent) => dirent.isDirectory());
const posts = [];
for (const { name } of rawPosts) {
try {
await access(postPath(name), constants.R_OK);
posts.push(name);
} catch {
continue;
}
}
return `
export const posts = new Set(${JSON.stringify(posts)});
`;
}
},
};
}