-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgatsby-node.js
98 lines (86 loc) · 2.39 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
const { createFilePath } = require("gatsby-source-filesystem");
const path = require(`path`);
// This creates a field called `slug` for us to access in every markdown files source tree
exports.onCreateNode = ({ node, getNode, actions }) => {
const { createNodeField } = actions;
if (node.internal.type === `MarkdownRemark`) {
const slug = createFilePath({
node,
getNode,
basePath: `content/blog/`,
trailingSlash: false,
});
createNodeField({
node,
name: `slug`,
value: `/blog${slug}`,
});
}
};
// Happens only after the adding of file nodes and updating of the Graphql schema so it can query
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions;
const blogPostTemplate = path.resolve(`src/templates/blog-post.jsx`);
const blogShareTemplate = path.resolve(`src/templates/blog-share-image.jsx`);
const blogCategoryTemplate = path.resolve(`src/templates/blog-category.jsx`);
const result = await graphql(`
query {
allMarkdownRemark {
edges {
node {
fields {
slug
}
frontmatter {
title
category
}
}
}
}
}
`);
if (result.errors) {
throw result.errors;
}
// console.log(JSON.stringify(result, null, 2));
const posts = result.data.allMarkdownRemark.edges;
const categories = [];
posts.forEach(post => {
if (!categories.includes(post.node.frontmatter.category)) {
categories.push(post.node.frontmatter.category);
}
});
// Create blog category pages
categories.forEach(category => {
createPage({
path: `/blog/${category.toLowerCase()}`,
component: blogCategoryTemplate,
context: {
category: category,
},
});
});
// Create blog post pages
posts.forEach((post, index) => {
createPage({
// Path for the page
path: post.node.fields.slug,
component: blogPostTemplate,
context: {
// This is inserted as prop to page component
slug: post.node.fields.slug,
},
});
// Create OG image for each blog post
if (process.env.NODE_ENV === "development") {
createPage({
path: `${post.node.fields.slug}/og_image`,
component: blogShareTemplate,
context: {
slug: post.node.fields.slug,
},
});
}
});
};