-
Notifications
You must be signed in to change notification settings - Fork 4
/
gatsby-node.js
263 lines (242 loc) · 6.61 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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
const fs = require(`fs`)
const path = require("path")
const { createFilePath } = require(`gatsby-source-filesystem`)
// Quick-and-dirty helper to convert strings into URL-friendly slugs.
const slugify = str => {
const slug = str
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/(^-|-\$)+/g, "")
return slug
}
// Make sure the data directory exists
exports.onPreBootstrap = ({ reporter }, options) => {
const contentPath = options.contentPath || "content"
if (!fs.existsSync(contentPath)) {
reporter.info(`creating the ${contentPath} directory`)
fs.mkdirSync(contentPath)
}
}
// Define the "BlogPost" type
// is there a way to just grab everything on an mdx node? no body/excerpt/timetoread/...
// should I do this in createSchemaCustomization or sourceNodes? What's the difference?
exports.sourceNodes = ({ actions, schema }) => {
// either SDL or graphql-js!
actions.createTypes(`
type Tag {
name: String
slug: String
}`)
actions.createTypes(`
type BlogPost implements Node {
id: ID!
slug: String!
title: String!
date: Date! @dateformat
author: String!
tags: [Tag]!
keywords: [String]!
excerpt(pruneLength: Int = 140): String!
body: String!
cover: File @fileByRelativePath
timeToRead: Int
tableOfContents(maxDepth: Int = 6): JSON
}
`)
}
// helper that grabs the mdx resolver when given a string fieldname
const mdxResolverPassthrough = fieldName => async (
source,
args,
context,
info
) => {
const type = info.schema.getType(`Mdx`)
const mdxNode = context.nodeModel.getNodeById({
id: source.parent,
})
const resolver = type.getFields()[fieldName].resolve
const result = await resolver(mdxNode, args, context, {
fieldName,
})
return result
}
// Define resolvers for custom fields
exports.createResolvers = ({ createResolvers }) => {
createResolvers({
BlogPost: {
excerpt: {
resolve: mdxResolverPassthrough(`excerpt`),
},
body: {
resolve: mdxResolverPassthrough(`body`),
},
timeToRead: {
resolve: mdxResolverPassthrough(`timeToRead`),
},
tableOfContents: {
resolve: mdxResolverPassthrough(`tableOfContents`),
},
},
})
}
exports.onCreateNode = (
{ node, actions, getNode, createNodeId, createContentDigest },
options
) => {
const { createNode, createParentChildLink } = actions
const contentPath = options.contentPath || "content"
// Make sure it's an MDX node
if (node.internal.type !== `Mdx`) {
return
}
// Create source field (according to contentPath)
const fileNode = getNode(node.parent)
const source = fileNode.sourceInstanceName
if (node.internal.type === `Mdx` && source === contentPath) {
let slug = createFilePath({ node, getNode })
if (slug.endsWith("/")) {
// if user entered basePath that ends in "/"
slug = slug.slice(0, -1)
}
const fieldData = {
title: node.frontmatter.title,
tags: (node.frontmatter.tags || []).map(tag => ({
name: tag,
slug: slugify(tag),
})),
slug,
date: node.frontmatter.date,
author: node.frontmatter.author,
keywords: node.frontmatter.keywords,
cover: node.frontmatter.cover,
}
// create a BlogPost node that satisfies the BlogPost type we created in createTypes
createNode({
...fieldData,
// Required fields.
id: createNodeId(`${node.id} >>> BlogPost`),
parent: node.id,
children: [],
internal: {
type: `BlogPost`,
contentDigest: createContentDigest(fieldData),
content: JSON.stringify(fieldData),
description: `Blog Posts`,
},
})
createParentChildLink({ parent: fileNode, child: node })
}
}
exports.createPages = async ({ actions, graphql, reporter }, options) => {
const basePath = options.basePath || "/"
const result = await graphql(`
query createPagesQuery {
allBlogPost(sort: { fields: date, order: DESC }) {
edges {
node {
title
slug
id
tags {
name
slug
}
}
}
}
}
`)
if (result.errors) {
reporter.panic("error loading data from graphql", result.error)
return
}
const { allBlogPost } = result.data
const posts = allBlogPost.edges
// create a page for each blogPost
posts.forEach(({ node: post }, i) => {
const next = i === 0 ? null : posts[i - 1].node
const prev = i === posts.length - 1 ? null : posts[i + 1].node
const { slug } = post
actions.createPage({
path: path.join(basePath, slug),
component: require.resolve("./src/templates/blog-post.js"),
context: {
slug,
prev,
next,
basePath,
},
})
})
// create (paginated) blog-list page(s)
let numPages
let postsPerPage
let prefixPath
if (options.pagination) {
prefixPath = options.pagination.prefixPath || ""
postsPerPage = options.pagination.postsPerPage || 6
numPages = Math.ceil(posts.length / postsPerPage)
} else {
prefixPath = ""
numPages = 1
}
Array.from({
length: numPages,
}).forEach((_, index) => {
const paginationContext = options.pagination
? {
limit: postsPerPage,
skip: index * postsPerPage,
numPages,
currentPage: index + 1,
prefixPath,
}
: {}
actions.createPage({
path:
index === 0
? basePath
: path.join(basePath, prefixPath, `${index + 1}`),
component: require.resolve("./src/templates/blog-posts.js"),
context: {
...paginationContext,
basePath,
},
})
})
// flatten tags per post into single array
const tagListDuplicates = posts.reduce((acc, post) => {
return acc.concat(post.node.tags)
}, [])
// filter duplicates from an array of tag objects and add amount instead
const tagList = tagListDuplicates.reduce((acc, tag) => {
const existingTag = acc.find(item => tag.slug === item.slug)
if (existingTag) {
existingTag.amount += 1
return acc
}
return [...acc, { ...tag, amount: 1 }]
}, [])
// create tag-list page
actions.createPage({
path: path.join(basePath, "tag"),
component: require.resolve("./src/templates/tags.js"),
context: {
tagList,
basePath,
},
})
// create a page for each tag
tagList.forEach(tag => {
actions.createPage({
path: path.join(basePath, "tag", tag.slug),
component: require.resolve("./src/templates/tag.js"),
context: {
tag,
slug: tag.slug,
basePath,
},
})
})
}