-
Notifications
You must be signed in to change notification settings - Fork 0
/
gatsby-node.js
70 lines (67 loc) · 2.01 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
//gatsby api to create the pages programmatically based on the data fetched
exports.createPages = async ({ graphql, actions, reporter }) => {
const { createPage } = actions
// aliased query with 2 datasources
const multipleDataQuery = await graphql(`
{
ContentFulItems: allContentfulBlogPost {
edges {
node {
slug
title
body {
childMarkdownRemark {
html
}
}
}
}
}
externalGraphQL: rickAndMorty {
characters {
results {
id
name
status
species
image
gender
}
}
}
}
`)
// checks if there's errors, puts them on the console
if (multipleDataQuery.errors) {
reporter.panicOnBuild(`Error while running GraphQL query.`)
return
}
// destructures the data
const {data}= multipleDataQuery
const {ContentFulItems,externalGraphQL}= data
// will create a page based on each item from contentful
ContentFulItems.edges.forEach(element => {
// generates a random number to fetch a item from the second query.
const characterPos= Math.floor(Math.random() * (externalGraphQL.characters.results.length - 1 + 1)) + 1;
//
/**
* create page api call to generate the page based on contentful.
* path will be where the page will "live"
* component will be the template used to display the data
* context is a special gatsby prop that allows injecting data from node to the actual page.
* to access it you'll have get the data from pageContext prop ( see the template)
*
*/
createPage({
path:`/${element.node.slug}/`,
component:require.resolve('./src/templates/dummy-template.js'),
context:{
contents:{
title:element.node.title,
content:element.node.body.childMarkdownRemark.html
},
AuthorData:externalGraphQL.characters.results[characterPos]
}
})
});
}