-
Notifications
You must be signed in to change notification settings - Fork 0
/
gatsby-node.js
102 lines (92 loc) · 2.37 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
96
97
98
99
100
101
102
const path = require("path")
const { createFilePath } = require("gatsby-source-filesystem")
const PostTemplate = path.resolve("./src/templates/post-template.js")
const BlogTemplate = path.resolve("./src/templates/blog-template.js")
const ProductTemplate = path.resolve("./src/templates/product-template.js")
/**
* Create individual slugs/file paths for each Markdown post file.
*/
exports.onCreateNode = ({ node, getNode, actions }) => {
const { createNodeField } = actions
if (node.internal.type === "MarkdownRemark") {
const slug = createFilePath({ node, getNode, basePath: "posts" })
createNodeField({
node,
name: "slug",
value: slug,
})
}
}
/**
* Create pages for each individual slug that was created above for blogs,
* as well as pages for each individual product on contentful.
*/
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions
const result = await graphql(`
{
allMarkdownRemark(limit: 1000) {
edges {
node {
fields {
slug
}
}
}
}
allContentfulProduct {
totalCount
edges {
node {
slug
}
}
}
}
`)
const posts = result.data.allMarkdownRemark.edges
posts.forEach(({ node: post }) => {
createPage({
path: `posts${post.fields.slug}`,
component: PostTemplate,
context: {
slug: post.fields.slug,
},
})
})
/**
* Pagination for blog posts on blog page.
*/
const postsPerPage = 2
const totalPages = Math.ceil(posts.length / postsPerPage)
Array.from({ length: totalPages }).forEach((_, index) => {
const currentPage = index + 1
const isFirstPage = index === 0
const isLastPage = currentPage === totalPages
createPage({
path: isFirstPage ? "/blog" : `/blog/${currentPage}`,
component: BlogTemplate,
context: {
limit: postsPerPage,
skip: index * postsPerPage,
isFirstPage,
isLastPage,
currentPage,
totalPages,
},
})
})
/**
* Pages for products
*/
const products = result.data.allContentfulProduct.edges
products.forEach(({ node: product }) => {
createPage({
path: `/products/${product.slug}`,
component: ProductTemplate,
context: {
slug: product.slug,
},
})
})
}