-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
gatsby-node.js
68 lines (61 loc) · 1.89 KB
/
gatsby-node.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
59
60
61
62
63
64
65
66
67
68
const jsYaml = require(`js-yaml`)
const _ = require(`lodash`)
const path = require(`path`)
function shouldOnCreateNode({ node }) {
return node.internal.mediaType === `text/yaml`
}
async function onCreateNode(
{ node, actions, loadNodeContent, createNodeId, createContentDigest },
pluginOptions
) {
function getType({ node, object, isArray }) {
if (pluginOptions && _.isFunction(pluginOptions.typeName)) {
return pluginOptions.typeName({ node, object, isArray })
} else if (pluginOptions && _.isString(pluginOptions.typeName)) {
return pluginOptions.typeName
} else if (node.internal.type !== `File`) {
return _.upperFirst(_.camelCase(`${node.internal.type} Yaml`))
} else if (isArray) {
return _.upperFirst(_.camelCase(`${node.name} Yaml`))
} else {
return _.upperFirst(_.camelCase(`${path.basename(node.dir)} Yaml`))
}
}
function transformObject(obj, id, type) {
const yamlNode = {
...obj,
id,
children: [],
parent: node.id,
internal: {
contentDigest: createContentDigest(obj),
type,
},
}
if (obj.id) {
yamlNode[`yamlId`] = obj.id
}
createNode(yamlNode)
createParentChildLink({ parent: node, child: yamlNode })
}
const { createNode, createParentChildLink } = actions
const content = await loadNodeContent(node)
const parsedContent = jsYaml.load(content)
if (_.isArray(parsedContent)) {
parsedContent.forEach((obj, i) => {
transformObject(
obj,
createNodeId(`${node.id} [${i}] >>> YAML`),
getType({ node, object: obj, isArray: true })
)
})
} else if (_.isPlainObject(parsedContent)) {
transformObject(
parsedContent,
createNodeId(`${node.id} >>> YAML`),
getType({ node, object: parsedContent, isArray: false })
)
}
}
exports.shouldOnCreateNode = shouldOnCreateNode
exports.onCreateNode = onCreateNode