forked from dliuproduction/gatsby-starter-prismic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gatsby-node.js
77 lines (68 loc) · 1.83 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
const _ = require('lodash')
// graphql function doesn't throw an error so we have to check to check for the result.errors to throw manually
const wrapper = (promise) =>
promise.then((result) => {
if (result.errors) {
throw result.errors
}
return result
})
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions
const postTemplate = require.resolve('./src/templates/post.jsx')
const categoryTemplate = require.resolve('./src/templates/category.jsx')
const result = await wrapper(
graphql(`
{
allPrismicPost {
edges {
node {
id
uid
data {
categories {
category {
document {
data {
name
}
}
}
}
}
}
}
}
}
`)
)
const categorySet = new Set()
const postsList = result.data.allPrismicPost.edges
// Double check that the post has a category assigned
postsList.forEach((edge) => {
if (edge.node.data.categories[0].category) {
edge.node.data.categories.forEach((cat) => {
categorySet.add(cat.category.document[0].data.name)
})
}
// The uid you assigned in Prismic is the slug!
createPage({
path: `/${edge.node.uid}`,
component: postTemplate,
context: {
// Pass the unique ID (uid) through context so the template can filter by it
uid: edge.node.uid,
},
})
})
const categoryList = Array.from(categorySet)
categoryList.forEach((category) => {
createPage({
path: `/categories/${_.kebabCase(category)}`,
component: categoryTemplate,
context: {
category,
},
})
})
}