-
-
Notifications
You must be signed in to change notification settings - Fork 103
/
on-create-node.ts
60 lines (52 loc) 路 1.5 KB
/
on-create-node.ts
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
59
60
import { CreateNodeArgs, Node } from "gatsby";
import { getReferences } from "./get-references";
import { PluginOptions, resolveOptions } from "./options";
import { clearInboundReferences, setCachedNode } from "./cache";
import { findTopLevelHeading } from "./markdown-utils";
function getTitle(node: Node, content: string) {
if (
typeof node.frontmatter === "object" &&
node.frontmatter &&
"title" in node.frontmatter &&
// @ts-ignore
node.frontmatter["title"]
) {
// @ts-ignore
return node.frontmatter["title"] as string;
}
return findTopLevelHeading(content) || "";
}
function getAliases(node: Node) {
if (
typeof node.frontmatter === "object" &&
node.frontmatter &&
"aliases" in node.frontmatter &&
// @ts-ignore
Array.isArray(node.frontmatter["aliases"])
) {
// @ts-ignore
return node.frontmatter["aliases"] as string[];
}
return [];
}
export const onCreateNode = async (
{ cache, node, loadNodeContent }: CreateNodeArgs,
_options?: PluginOptions
) => {
const options = resolveOptions(_options);
// if we shouldn't process this node, then return
if (!options.types.includes(node.internal.type)) {
return;
}
const content = await loadNodeContent(node);
const outboundReferences = getReferences(content);
const title = getTitle(node, content);
const aliases = getAliases(node);
await clearInboundReferences(cache);
await setCachedNode(cache, node.id, {
node,
outboundReferences,
title,
aliases,
});
};