-
Notifications
You must be signed in to change notification settings - Fork 1
/
gatsby-node.js
86 lines (82 loc) 路 2.31 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
const path = require(`path`);
const kebabCase = require(`lodash.kebabcase`);
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions;
const { data } = await graphql(`
{
allMarkdownRemark(sort: { order: DESC, fields: frontmatter___date }) {
edges {
node {
frontmatter {
slug
title
category
}
id
}
}
}
}
`);
//Creating the pages programmatically
const postsPerPage = 3;
const numPages = Math.ceil(
data.allMarkdownRemark.edges.length / postsPerPage
);
const blogListLayout = path.resolve(`src/templete/allPosts/allPosts.jsx`);
Array.from({ length: numPages }).forEach((_, i) => {
createPage({
path: i === 0 ? `blog/1` : `blog/${i + 1}`,
component: blogListLayout,
context: {
limit: postsPerPage,
skip: i * postsPerPage,
currentPage: i + 1,
numPages,
},
});
});
// Create Single Post
const posts = data.allMarkdownRemark.edges;
posts.forEach(({ node }, index) => {
createPage({
path: `/blog/${node.frontmatter.slug}`,
component: path.resolve(`src/templete/blog/post.jsx`),
context: {
slug: node.frontmatter.slug,
},
});
});
// getting Categories
const blogCategoryLayout = path.resolve(
`src/templete/blogCategory/blogCategory.jsx`
);
const categories = [];
posts.forEach(post =>
post.node.frontmatter.category.forEach(cat => categories.push(cat))
);
const countCategories = categories.reduce((acc, curr) => {
acc[curr] = (acc[curr] || 0) + 1;
return acc;
}, {});
const allCategories = Object.keys(countCategories);
allCategories.forEach((category, _i) => {
const link = `/blog/category/${kebabCase(category)}`;
Array.from({
length: Math.ceil(countCategories[category] / postsPerPage),
}).forEach((_, i) =>
createPage({
path: i === 0 ? link : `${link}/page/${i + 1}`,
component: blogCategoryLayout,
context: {
allCategories: allCategories,
category: category,
limit: postsPerPage,
skip: i * postsPerPage,
currentPage: i + 1,
numPages: Math.ceil(countCategories[category] / postsPerPage),
},
})
);
});
};