-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
Copy pathgatsby-node.js
66 lines (59 loc) · 1.86 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
const _ = require(`lodash`)
const path = require(`path`)
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} Json`))
} else if (isArray) {
return _.upperFirst(_.camelCase(`${node.name} Json`))
} else {
return _.upperFirst(_.camelCase(`${path.basename(node.dir)} Json`))
}
}
function transformObject(obj, id, type) {
const jsonNode = {
...obj,
id,
children: [],
parent: node.id,
internal: {
contentDigest: createContentDigest(obj),
type,
},
}
createNode(jsonNode)
createParentChildLink({ parent: node, child: jsonNode })
}
const { createNode, createParentChildLink } = actions
// We only care about JSON content.
if (node.internal.mediaType !== `application/json`) {
return
}
const content = await loadNodeContent(node)
const parsedContent = JSON.parse(content)
if (_.isArray(parsedContent)) {
parsedContent.forEach((obj, i) => {
transformObject(
obj,
obj.id ? String(obj.id) : createNodeId(`${node.id} [${i}] >>> JSON`),
getType({ node, object: obj, isArray: true })
)
})
} else if (_.isPlainObject(parsedContent)) {
transformObject(
parsedContent,
parsedContent.id
? String(parsedContent.id)
: createNodeId(`${node.id} >>> JSON`),
getType({ node, object: parsedContent, isArray: false })
)
}
}
exports.onCreateNode = onCreateNode