-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
Copy pathgatsby-node.js
78 lines (70 loc) · 2.17 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
69
70
71
72
73
74
75
76
77
78
const _ = require(`lodash`)
const path = require(`path`)
function shouldOnCreateNode({ node }) {
// We only care about JSON content.
return node.internal.mediaType === `application/json`
}
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`))
}
}
async function transformObject(obj, id, type) {
const jsonNode = {
...obj,
id,
children: [],
parent: node.id,
internal: {
contentDigest: createContentDigest(obj),
type,
},
}
if (obj.id) {
jsonNode[`jsonId`] = obj.id
}
await createNode(jsonNode)
createParentChildLink({ parent: node, child: jsonNode })
}
const { createNode, createParentChildLink } = actions
const content = await loadNodeContent(node)
let parsedContent
try {
parsedContent = JSON.parse(content)
} catch {
const hint = node.absolutePath
? `file ${node.absolutePath}`
: `in node ${node.id}`
throw new Error(`Unable to parse JSON: ${hint}`)
}
if (_.isArray(parsedContent)) {
for (let i = 0, l = parsedContent.length; i < l; i++) {
const obj = parsedContent[i]
await transformObject(
obj,
createNodeId(`${node.id} [${i}] >>> JSON`),
getType({ node, object: obj, isArray: true })
)
}
} else if (_.isPlainObject(parsedContent)) {
await transformObject(
parsedContent,
createNodeId(`${node.id} >>> JSON`),
getType({ node, object: parsedContent, isArray: false })
)
}
}
exports.shouldOnCreateNode = shouldOnCreateNode
exports.onCreateNode = onCreateNode