/
gatsby-node.js
84 lines (70 loc) · 2.26 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
79
80
81
82
83
84
const csv = require(`csvtojson`)
const _ = require(`lodash`)
const { typeNameFromFile } = require(`./index`)
const convertToJson = (data, options) =>
csv(options)
.fromString(data)
.then(jsonData => jsonData, new Error(`CSV to JSON conversion failed!`))
function shouldOnCreateNode({ node }, pluginOptions = {}) {
const { extension } = node
const { extensions } = pluginOptions
return extensions ? extensions.includes(extension) : extension === `csv`
}
async function onCreateNode(
{ node, actions, loadNodeContent, createNodeId, createContentDigest },
pluginOptions
) {
const { createNode, createParentChildLink } = actions
// Destructure out our custom options
const { typeName, nodePerFile, ...options } = pluginOptions || {}
// Load file contents
const content = await loadNodeContent(node)
// Parse
const parsedContent = await convertToJson(content, options)
// Generate the type
function getType({ node, object }) {
if (pluginOptions && _.isFunction(typeName)) {
return pluginOptions.typeName({ node, object })
} else if (pluginOptions && _.isString(typeName)) {
return _.upperFirst(_.camelCase(typeName))
} else {
return typeNameFromFile({ node })
}
}
// Generate the new node
function transformObject(obj, i) {
const csvNode = {
...obj,
id:
obj.id ??
createNodeId(`${node.id} [${i}] >>> ${node.extension.toUpperCase()}`),
children: [],
parent: node.id,
internal: {
contentDigest: createContentDigest(obj),
// TODO make choosing the "type" a lot smarter. This assumes
// the parent node is a file.
// PascalCase
type: getType({ node, object: parsedContent }),
},
}
createNode(csvNode)
createParentChildLink({ parent: node, child: csvNode })
}
if (_.isArray(parsedContent)) {
if (pluginOptions && nodePerFile) {
if (pluginOptions && _.isString(nodePerFile)) {
transformObject({ [nodePerFile]: parsedContent }, 0)
} else {
transformObject({ items: parsedContent }, 0)
}
} else {
_.each(parsedContent, (obj, i) => {
transformObject(obj, i)
})
}
}
return
}
exports.shouldOnCreateNode = shouldOnCreateNode
exports.onCreateNode = onCreateNode