forked from AndreasFaust/gatsby-source-custom-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gatsby-node.js
executable file
·57 lines (49 loc) · 1.56 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
const fetch = require('node-fetch')
const createNodeEntities = require('./createNodeEntities')
const normalizeKeys = require('./utils/normalizeKeys')
const flattenEntities = require('./utils/flattenEntities')
const loadImages = require('./utils/loadImages')
const getUrl = require('./utils/getUrl')
const getTypeDefs = require('./utils/getTypeDefs')
const buildNode = require('./utils/buildNode')
exports.sourceNodes = async (
{
actions, createNodeId, createContentDigest, store, cache
},
configOptions
) => {
const { createNode, createTypes, touchNode } = actions
const {
url,
headers,
rootKey = 'customAPI',
imageKeys = ['image'],
schemas = {}
} = configOptions
const URL = getUrl(process.env.NODE_ENV, url)
const data = await fetch(URL, { headers }).then(res => res.json()).catch(err => console.log(err))
const typeDefs = getTypeDefs(schemas, imageKeys)
createTypes(typeDefs)
// build entities and correct schemas, where necessary
let entities = flattenEntities(createNodeEntities({
name: rootKey,
data,
schemas,
createNodeId
}))
// check for problematic keys
entities = entities.map(entity => ({
...entity,
data: normalizeKeys(entity.data)
}))
// load images or default-dummy-image
entities = await loadImages({
entities, imageKeys, createNode, createNodeId, touchNode, store, cache, createContentDigest
})
// build gatsby-node-object
entities = entities.map(entity => buildNode({ entity, createContentDigest }))
// render nodes
entities.forEach((entity) => {
createNode(entity)
})
}