This repository has been archived by the owner on Jun 9, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgatsby-node.js
60 lines (49 loc) · 2.31 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
/**
* Implement Gatsby's Node APIs in this file.
*/
const axios = require('axios');
const crypto = require('crypto');
// exports.sourceNodes = async ({ boundActionCreators }) => {
exports.sourceNodes = ({boundActionCreators}) => {
const {createNode} = boundActionCreators;
return new Promise((resolve, reject) => {
// fetch raw data from the api
// const fetchProducts = () => axios.get(`https://raw.githubusercontent.com/Flaconi/coding-challenges/master/senior-frontend-engineer/resources/productlist.json`);
// await for results
// const res = await fetchProducts();
axios.get(`https://raw.githubusercontent.com/Flaconi/coding-challenges/master/frontend-engineer/resources/productlist.json`)
.then(res => {
// map into these results and create nodes
res.data.map((product, i) => {
// Create your node object
const productNode = {
// Required fields
id: product.id,
parent: `__SOURCE__`,
internal: {
type: `products`,
// name of the graphQL query --> allproducts {}
// contentDigest will be added just after, but it is required
},
children: [],
// Other fields that you want to query with graphQl
name: product.name,
slug: product.slug,
brand: product.brand,
type: product.type,
image: product.image,
price: product.price,
size: product.size,
rating: product.rating,
}
// Get content digest of node. (Required field)
const contentDigest = crypto.createHash(`md5`).update(JSON.stringify(productNode)).digest(`hex`);
// add it to productNode
productNode.internal.contentDigest = contentDigest;
// Create node with the gatsby createNode() API
createNode(productNode);
});
resolve();
});
});
}