/
gatsby-node.js
52 lines (45 loc) · 1.24 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
/**
* Implement Gatsby's Node APIs in this file.
*
* See: https://www.gatsbyjs.org/docs/node-apis/
*/
// You can delete this file if you're not using it
// Asynchronous function to generate pages after retrieving data
// Destructure graphql and actions from API
exports.createPages = async ({ graphql, actions }) => {
// Destructure createPage function from actions
const { createPage } = actions
// Wait for GraphQL to get data
const result = await graphql(`
query {
allSanityProject {
edges {
node {
title
slug {
current
}
}
}
}
}
`)
// Throw errors if there is a problem retrieving data
if (result.errors) {
throw result.errors
}
// Map data to a variable, or set to empty array if data is nonexistent
const projects = result.data.allSanityProject.edges || []
// For each project, generate a slug from the data and create a page using path, component, and variables
// Then, pass in the project data to each page
projects.forEach(({node}) => {
createPage({
// Create a path name
path: `/projects/${node.slug.current}`,
// Assign page to a template
component: require.resolve('./src/templates/project.js'),
// Pass in data to page
context: {title: node.title},
})
})
}