-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgatsby-node.js
95 lines (89 loc) · 2.66 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/**
* Implement Gatsby's Node APIs in this file.
*
* See: https://www.gatsbyjs.org/docs/node-apis/
*/
const path = require(`path`)
const { createFilePath } = require(`gatsby-source-filesystem`)
// Process and create paths for Markdown pages
exports.onCreateNode = ({ node, getNode, actions }) => {
const { createNodeField } = actions
if (node.internal.type === `MarkdownRemark`) {
const slug = createFilePath({ node, getNode, basePath: `content` })
createNodeField({
node,
name: "slug",
value: slug,
})
// Extract module name from path, used for file seperation
const module = /guide\/(\w+)/.exec(slug)[1]
createNodeField({
node,
name: "module",
value: module,
})
}
}
// Now actually create the pages
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions
// We want slug (link to where page is), plus the title (for displaying on previous/next pages)
const result = await graphql(`
{
allMarkdownRemark(
sort: { fields: [fields___module, frontmatter___step] }
) {
edges {
node {
fields {
module
slug
}
frontmatter {
step
title
}
}
}
}
}
`)
let nextForModule = function(step, steps, index) {
// end of step list obviously means no more steps
if (index !== steps.length - 1) {
// if the "next step" is from a different module, just return a null reference to avoid accidental crossover
let nextStep = steps[index + 1].node
return nextStep.fields.module === step.node.fields.module
? nextStep
: null
}
return null
}
let previousForModule = function(step, steps, index) {
// start of step list means no previous step
if (index !== 0) {
// if the "previous step" is from a different module, just return a null reference to avoid accidental crossover
let previousStep = steps[index - 1].node
return previousStep.fields.module === step.node.fields.module
? previousStep
: null
}
return null
}
const steps = result.data.allMarkdownRemark.edges
steps.forEach((step, index) => {
// save previous & next steps if they exist for the module
const next = nextForModule(step, steps, index)
const previous = previousForModule(step, steps, index)
createPage({
path: step.node.fields.slug,
component: path.resolve(`./src/templates/guide-step.js`),
context: {
// allows access to slug as GraphQL variable
slug: step.node.fields.slug,
previous,
next,
},
})
})
}