-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgatsby-node.js
More file actions
48 lines (39 loc) · 1.36 KB
/
gatsby-node.js
File metadata and controls
48 lines (39 loc) · 1.36 KB
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
const axios = require('axios')
const fetchAllCharacters = (response = {}, characters = []) => {
if (!response.info || response.info.next) {
return axios(response.info ? response.info.next : 'https://rickandmortyapi.com/api/character')
.then(res => res.data)
.then(res => {
return fetchAllCharacters(res, characters.concat(res.results))
})
}
return characters
}
exports.sourceNodes = async function sourceNodes({ cache, actions, createNodeId, createContentDigest, reporter }, options) {
const CACHE_KEY = `characters`
let existing = await cache.get(CACHE_KEY)
if (!existing) {
reporter.info('Characters was not cached. Fetching new characters')
const characters = await fetchAllCharacters()
existing = characters
await cache.set(CACHE_KEY, characters)
} else {
reporter.info('Characters was cached. Moving on!')
}
for (let i = 0; i < existing.length; i++) {
const character = Object.assign({}, existing[i], {
id: existing[i].id.toString()
})
const node = {
id: createNodeId(`rick-and-morty-character-${character.id}`),
parent: null,
children: [],
internal: {
type: `RickAndMortyCharacter`,
content: JSON.stringify(character),
contentDigest: createContentDigest(character)
}
}
actions.createNode(Object.assign({}, node, character))
}
}