-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgatsby-node.ts
More file actions
97 lines (90 loc) · 2.58 KB
/
Copy pathgatsby-node.ts
File metadata and controls
97 lines (90 loc) · 2.58 KB
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
/**
* Implement Gatsby's Node APIs in this file.
* See: https://www.gatsbyjs.org/docs/node-apis/
*/
import type { GatsbyNode } from 'gatsby';
import path from 'path';
/**
* Disable generating source maps on Production
*/
export const onCreateWebpackConfig: GatsbyNode['onCreateWebpackConfig'] = ({
getConfig,
stage,
actions,
}) => {
if (getConfig().mode === 'production' && stage === 'build-javascript') {
actions.setWebpackConfig({
devtool: false,
});
}
};
export const createPages: GatsbyNode['createPages'] = async ({
actions,
graphql,
reporter,
}) => {
const { createPage } = actions;
/**
* Get path to blog post and blog list template
* So we can reference it later for Gatsby createPage API
*/
const blogPostTemplate = path.resolve('src/templates/blog-post.js');
const blogListTemplate = path.resolve('src/templates/blog-list.js');
/**
* Fetch all the markdown data to create blog list and blog post page dynamically
*/
const result = await graphql(`
{
allMarkdownRemark(sort: { frontmatter: { date: DESC } }, limit: 1000) {
edges {
node {
frontmatter {
path
title
}
}
}
}
}
`);
// Handle on errors
if (result.errors) {
reporter.panicOnBuild('Error while running GraphQL query.');
return;
}
const posts = (result.data as any).allMarkdownRemark.edges;
/**
* After we successfully pull all markdown data
* Then create blog list pages dynamically
* Also we pass context (pageContext) to the component template (blogListTemplate) for pagination
*/
const postsPerPage = 5;
const numberOfPages = Math.ceil(posts.length / postsPerPage);
Array.from({ length: numberOfPages }).forEach((_, i) => {
createPage({
path: i === 0 ? `/blog` : `/blog/${i + 1}`,
component: blogListTemplate,
context: {
limit: postsPerPage,
skip: i * postsPerPage,
numberOfPages,
currentPage: i + 1,
},
});
});
/**
* After we successfully pull all markdown data
* We also create blog posts for each markdown data
* Also we pass context (pageContext) to the component template (blogPostTemplate) for pagination to the next/previous blog post
*/
posts.forEach(({ node }: { node: any }, index: number) => {
createPage({
path: node.frontmatter.path,
component: blogPostTemplate,
context: {
previous: index === posts.length - 1 ? null : posts[index + 1].node,
next: index === 0 ? null : posts[index - 1].node,
},
});
});
};