-
Notifications
You must be signed in to change notification settings - Fork 2
/
gatsby-node.js
92 lines (80 loc) · 1.79 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
85
86
87
88
89
90
91
92
const crypto = require('crypto');
var nanoid = require('nanoid')
const fetch = require(`./fetch`)
const normalize = require(`./normalize`)
const { createRemoteFileNode } = require(`gatsby-source-filesystem`)
function getDescendantProp(obj, desc) {
var arr = desc.split(".");
while(arr.length && (obj = obj[arr.shift()]));
return obj;
}
exports.sourceNodes = async ({
actions,
store,
cache
}, {
name,
uri,
auth
}) => {
const { createNode } = actions;
// Create nodes here by downloading data
// from a remote API.
console.log(`Fetching JSON Data (${name})`)
let data = await fetch({uri, auth})
entities = normalize.standardizeKeys(data)
// Process data into nodes.
for (const document of entities) {
// Add the document
try {
await createNode({
...document,
id: nanoid(),
parent: null,
children: [],
mediaType: 'application/json',
internal: {
type: name,
contentDigest: crypto
.createHash(`md5`)
.update(JSON.stringify(document))
.digest(`hex`)
}
})
} catch (error) {
console.warn('error creating node', error)
}
}
console.log(`Finished Fetching JSON (${name})`)
return;
};
exports.onCreateNode = async ({
node,
store,
cache,
actions,
createNodeId
}, {
image_location = 'image.url',
name
}) => {
const { createNode } = actions
if (node.internal.type === name) {
let fileNode
const url = getDescendantProp(node, image_location)
try {
fileNode = await createRemoteFileNode({
url: url,
store,
cache,
createNode,
createNodeId,
})
} catch (e) {
console.warn('error', e)
}
if (fileNode) {
node.image___NODE = fileNode.id
}
}
}