-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathon-create-node.ts
61 lines (48 loc) · 1.65 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
61
import path from 'path';
import { defaults, isString } from 'lodash';
import traverse from 'traverse';
import {
defaultPluginOptions,
PluginOptions,
GatsbyFile,
MarkdownNode,
findMatchingFile,
} from '.';
import { slash } from './utils';
export type GatsbyPluginArgs = {
node: MarkdownNode;
getNodesByType: (type: string) => GatsbyFile[];
reporter: {
info: (msg: string, error?: Error) => void;
};
};
export const onCreateNode = (
{ node, getNodesByType }: GatsbyPluginArgs,
pluginOptions: PluginOptions
) => {
const options = defaults(pluginOptions, defaultPluginOptions);
if (node.fileAbsolutePath && node.internal.type === `MarkdownRemark` || node.internal.type === `Mdx`) {
const files = getNodesByType(`File`);
const directory = path.dirname(node.fileAbsolutePath);
// Deeply iterate through frontmatter data for absolute paths
traverse(node.frontmatter).forEach(function (value) {
if (!isString(value)) return;
if (!path.isAbsolute(value) || !path.extname(value)) return;
const paths = this.path.reduce<string[]>((acc, current) => {
acc.push(acc.length > 0 ? [acc, current].join('.') : current);
return acc;
}, []);
let shouldTransform = options.include.length < 1;
if (options.include.some((a) => paths.includes(a))) {
shouldTransform = true;
}
if (options.exclude.some((a) => paths.includes(a))) {
shouldTransform = false;
}
if (!shouldTransform) return;
const file = findMatchingFile(value, files, options);
const newValue = slash(path.relative(directory, file.absolutePath));
this.update(newValue);
});
}
};