-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgatsby-node.js
110 lines (97 loc) · 2.88 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
103
104
105
106
107
108
109
110
const path = require("path")
const { createFilePath } = require("gatsby-source-filesystem")
const categoriesInfo = require("./src/utils/categories-info")
// To add the url field to each post
exports.onCreateNode = ({ node, getNode, actions }) => {
const { createNodeField } = actions
// processing only markdown files
if (node.internal.type === "MarkdownRemark") {
const postFilePath = createFilePath({
node,
getNode,
})
//creating the url field
createNodeField({
node,
name: "url",
value: `/${postFilePath.slice(12)}`,
})
}
}
// to create pages dynamically
exports.createPages = ({ graphql, actions }) => {
const { createPage } = actions
return graphql(`
query {
allMarkdownRemark(sort: { fields: frontmatter___date, order: DESC }) {
edges {
node {
id
frontmatter {
category
}
fields {
url
}
}
}
distinct(field: frontmatter___category)
}
}
`).then(result => {
const posts = result.data.allMarkdownRemark.edges
const categories = result.data.allMarkdownRemark.distinct
const postsPerPage = 5
// creating pages to each post
posts.forEach(({ node }) => {
createPage({
path: node.fields.url,
component: path.resolve(`./src/templates/blog-post.js`),
context: {
id: node.id,
url: node.fields.url,
category: node.frontmatter.category,
},
})
})
// creating pages by pagination
const numberOfPages = Math.ceil(posts.length / postsPerPage)
Array.from({ length: numberOfPages }).forEach((_, index) => {
const currentPage = index + 1
createPage({
path: index === 0 ? "/" : `/${currentPage}`,
component: path.resolve("./src/templates/blog-list.js"),
context: {
limit: postsPerPage,
skip: index * postsPerPage,
numberOfPages,
currentPage,
},
})
})
// creating pages for each category whith pagination
categories.forEach(categoryId => {
const totalPostsPerCategory = posts.reduce(
(acc, curr) =>
curr.node.frontmatter.category === categoryId ? acc + 1 : acc,
0
)
const numberOfPages = Math.ceil(totalPostsPerCategory / postsPerPage)
const { slug } = categoriesInfo(categoryId)
Array.from({ length: numberOfPages }).forEach((_, index) => {
const currentPage = index + 1
createPage({
path: index === 0 ? `/${slug}` : `/${slug}/${currentPage}`,
component: path.resolve("./src/templates/posts-per-category.js"),
context: {
limit: postsPerPage,
skip: index * postsPerPage,
numberOfPages,
currentPage,
categoryId,
},
})
})
})
})
}