-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathgatsby-node.js
480 lines (415 loc) · 13.5 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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
require('typescript-require');
const _ = require('lodash');
const fs = require('fs');
const ncp = require('ncp').ncp;
const Promise = require('bluebird');
const path = require('path');
const mkdirp = require('mkdirp');
const rimraf = require('rimraf');
const base64 = require('js-base64').Base64;
const {createFilePath} = require('gatsby-source-filesystem');
const postsSettings = require('./static/config/posts.json');
const siteSettings = require('./static/config/settings.json');
const postTemplate = path.resolve('./src/templates/post/index.tsx');
const postsTemplate = path.resolve('./src/templates/posts/index.tsx');
const tagTemplate = path.resolve('./src/templates/tag/index.tsx');
const categoryTemplate = path.resolve('./src/templates/category/index.tsx');
const getTags = (edges) => {
const tags = [];
_.each(edges, (edge) => {
if (_.get(edge, 'node.frontmatter.tags')) {
for (let i = 0; i < edge.node.frontmatter.tags.length; i++) {
tags.push(edge.node.frontmatter.tags[i]);
}
}
});
return tags;
};
const makeSureEndsWithSlash = (url) => {
url += url.endsWith('/') ? '' : '/';
return url;
};
const paginatePosts = (createPage, postsEdges) => {
const pathPrefix = postsSettings.pathPrefix || 'posts';
const filterOutPages = (edges) => {
const filteredPosts = [];
edges.map((post) => {
// We need to filter out from pagination the default post also (supported cards)
if (post.node.frontmatter.isPage !== true && post.node.fileAbsolutePath.indexOf('static/content/collections/posts') !== -1) {
filteredPosts.push(post);
}
});
return filteredPosts;
};
// Setup pagination but start with filtering out the
// posts that are pages otherwise we will have more pagination
// pages and the template will fail to recognize some
const posts = filterOutPages(postsEdges);
const postsPerPage = 6;
const numPages = Math.ceil(posts.length / postsPerPage);
_.times(numPages, i => {
createPage({
path : makeSureEndsWithSlash(i === 0 ? `${pathPrefix}` : `${pathPrefix}/${i + 1}`),
component: postsTemplate,
context : {
limit : postsPerPage,
skip : i * postsPerPage,
numPages,
currentPage: i + 1,
},
});
});
// Create posts and pages.
_.each(postsEdges, (edge, index) => {
const slug = edge.node.fields.slug;
const previous = index === postsEdges.length - 1 ? null : postsEdges[index + 1].node;
const next = index === 0 ? null : postsEdges[index - 1].node;
// create posts
createPage({
path : makeSureEndsWithSlash(slug),
component: postTemplate,
context : {
slug,
previous,
next,
tags : edge.node.frontmatter.tags || [],
categories: edge.node.frontmatter.categories,
},
});
});
};
const paginateTags = (createPage, posts) => {
// Setup pagination
const tags = _.uniq(getTags(posts));
if (tags.length <= 0) return;
const getPostsByTag = (tag) => {
const postsByTag = [];
posts.map((post) => {
const p = post.node;
if (p.frontmatter.tags && p.frontmatter.tags.length > 0 && p.frontmatter.tags.includes(tag)) {
postsByTag.push(p.node);
}
});
return postsByTag;
};
const paginateTag = (tag) => {
const postsPerPage = 6;
const tagPosts = getPostsByTag(tag);
const numPages = Math.ceil(tagPosts.length / postsPerPage);
const slug = slugify(tag);
_.times(numPages, i => {
createPage({
path : makeSureEndsWithSlash(i === 0 ? `tag/${slug}` : `tag/${slug}/${i + 1}`),
component: tagTemplate,
context : {
limit : postsPerPage,
skip : i * postsPerPage,
numPages,
currentPage: i + 1,
tag,
slug : makeSureEndsWithSlash(slug),
},
});
});
};
// Make tag pages
tags.forEach(paginateTag);
};
const paginateCategories = (createPage, posts, categories) => {
if (categories.length <= 0) return;
const getPostsByCategory = (category) => {
const postsByCategory = [];
posts.map((post) => {
const p = post.node;
if (p.frontmatter.categories === category.frontmatter.title) {
postsByCategory.push(p.node);
}
});
return postsByCategory;
};
_.uniqBy(categories, 'node.id').forEach((category) => {
const c = category.node;
const postsPerPage = 6;
const categoryPosts = getPostsByCategory(c);
const numPages = Math.ceil(categoryPosts.length / postsPerPage);
const slug = c.fields.slug;
if (categoryPosts.length > 0) {
_.times(numPages, i => {
createPage({
path : makeSureEndsWithSlash(i === 0 ? slug : `${slug}${i + 1}`),
component: categoryTemplate,
context : {
limit : postsPerPage,
skip : i * postsPerPage,
numPages,
currentPage: i + 1,
category : c,
slug : makeSureEndsWithSlash(slug),
},
});
});
} else {
// the navbar component does a query on the categories but it can't know
// if the results have any posts in them so we have to make a page even if
// there will be no results to be shown
createPage({
path : makeSureEndsWithSlash(slug),
component: categoryTemplate,
context : {
limit : postsPerPage,
skip : 0,
numPages,
currentPage: 1,
category : c,
slug : makeSureEndsWithSlash(slug),
},
});
}
});
};
exports.createPages = ({graphql, actions}) => {
const {createPage} = actions;
return new Promise((resolve, reject) => {
resolve(
graphql(`
{
posts: allMarkdownRemark(filter: {fileAbsolutePath: {regex: "//collections/posts//"}}) {
edges {
node {
fields{
slug
}
frontmatter {
tags
isPage
created_at
categories
}
fileAbsolutePath
}
}
}
categories: allMarkdownRemark(filter: {fileAbsolutePath: {regex: "//collections/categories//"}}) {
edges {
node {
id
fields{
slug
}
frontmatter {
title
}
}
}
}
}
`).then((result) => {
if (result.errors) {
console.error(result.errors);
reject(result.errors);
}
const postsEdges = result.data.posts.edges;
const categoriesEdges = result.data.categories.edges;
paginatePosts(createPage, postsEdges);
paginateTags(createPage, postsEdges);
paginateCategories(createPage, postsEdges, categoriesEdges);
}),
);
});
};
const isNodeOfCollection = (node, collection) => node.internal.type === 'MarkdownRemark' &&
node.fileAbsolutePath.match(`collections/${collection}`);
// Will return only nodes that are from a given collection
const getCollectionNodes = (collection, getNodes) => {
return getNodes().filter(node => isNodeOfCollection(node, collection)) || [];
};
// Given a post node, returns the node of the author
const getPostAuthorNode = (postNode, getNodes) => {
return getCollectionNodes('authors', getNodes).find(node => {
return node.frontmatter.title === postNode.frontmatter.authors;
});
};
// Given a post node, returns the node of the category
const getPostCategoryNode = (postNode, getNodes) => {
return getCollectionNodes('categories', getNodes).find(node => {
return node.frontmatter.title === postNode.frontmatter.categories;
});
};
const mapCategoriesToPostNode = (node, getNodes) => {
const category = getPostCategoryNode(node, getNodes);
// Netlify CMS does not (yet) support one to many relationships
// but we're adding an array to avoid introducing breaking changes
// once they do and we have to adapt
if (category) node.categories___NODES = [category.id];
};
const mapAuthorsToPostNode = (node, getNodes) => {
const author = getPostAuthorNode(node, getNodes);
// Same as above...an array is created
if (author) node.authors___NODES = [author.id];
};
const slugify = (text) => {
return text.toString().toLowerCase()
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/[^\w\-]+/g, '') // Remove all non-word chars
.replace(/\-\-+/g, '-') // Replace multiple - with single -
.replace(/^-+/, '') // Trim - from start of text
.replace(/-+$/, ''); // Trim - from end of text
};
/**
* Netlify cms supports custom slugs but not fully
* For example you can't add a slug config like: {{year}}/{{month}}/{{day}}
* and expect for it to work because the slashes will get replaced with
* dashes since Netlify CMS does NOT know how to deal with subfolders
* For a new blog this is not a big deal but it might be for a blog that
* is being imported from Wordpress which has this type of urls (I know
* because I faced this issue). The solution is to create the slug here
*/
const createFinalSlug = (post, slug) => {
// based on the posts settings
const slugConfig = postsSettings.slugStructure;
// SUPPORTED TOKENS
//
// {{slug}}: a url-safe version of the title field for the file
// {{year}}: 4-digit year of the file creation date
// {{month}}: 2-digit month of the file creation date
// {{day}}: 2-digit day of the month of the file creation date
// {{hour}}: 2-digit hour of the file creation date
// {{minute}}: 2-digit minute of the file creation date
// {{second}}: 2-digit second of the file creation date
const dt = new Date(post.frontmatter.created_at);
const mo = ('0' + (dt.getMonth() + 1)).slice(-2);
const day = ('0' + dt.getDate()).slice(-2);
const year = dt.getFullYear();
const hour = dt.getHours();
const minute = dt.getMinutes();
const second = dt.getSeconds();
return `/${slugConfig}/`
.replace('{{slug}}', slug)
.replace('{{year}}', year)
.replace('{{month}}', mo)
.replace('{{day}}', day)
.replace('{{hour}}', hour)
.replace('{{minute}}', minute)
.replace('{{second}}', second)
// replace double slashes with a single one
.replace(/\/+/g, '/');
};
// Creates a mapping between posts and authors, sets the slug
// and other required attributes
exports.sourceNodes = ({actions, getNodes, getNode}) => {
const {createNodeField} = actions;
getCollectionNodes('categories', getNodes).forEach(node => {
createNodeField({node, name: 'slug', value: `category${createFilePath({node, getNode})}`});
});
getCollectionNodes('posts', getNodes).forEach(node => {
mapAuthorsToPostNode(node, getNodes);
mapCategoriesToPostNode(node, getNodes);
// create the post slug
const slugPath = createFilePath({node, getNode});
createNodeField({node, name: 'slug', value: createFinalSlug(node, slugPath)});
});
};
const createReferencesField = (node, actions, getNodes) => {
const cPattern = /{"widget":"([a-zA-Z0-9-]+)","config":"(.*?)"}/;
function decodeWidgetDataObject(data) {
return JSON.parse(base64.decode(data));
}
if (!node.rawMarkdownBody) return;
const references = [];
node.rawMarkdownBody.split('\n').map(line => {
if (RegExp(cPattern).test(line)) {
const params = line.match(cPattern);
const widget = params[1];
const config = decodeWidgetDataObject(params[2]);
if (widget === 'qards-reference') {
// find the post that is referenced based on title
// TODO: check back with Netlify CMS and see if they made it possible to
// put an id in the valueField or a slug because the `title` field can
// change at any time and it's only a matter of time before we get into
// trouble with missing referenced posts
getCollectionNodes('posts', getNodes).forEach(searchNode => {
// this title match is inneficient! See above
if (searchNode.frontmatter.title === config.reference) {
references.push(searchNode.id);
}
});
}
}
});
node.references___NODES = references;
};
exports.onCreateWebpackConfig = ({stage, actions}) => {
const MomentLocalesPlugin = require('moment-locales-webpack-plugin');
if (stage === 'build-javascript') {
// Turn off source maps
actions.setWebpackConfig({
devtool: false,
});
}
actions.setWebpackConfig({
plugins: [
new MomentLocalesPlugin(),
],
});
};
exports.onPreBootstrap = () => {
// See gatsby-browser.js to learn why we do this
const customfontsDir = './public/custom-fonts';
const performanceMode = siteSettings.performanceMode;
const writeEmptyFile = () => {
return new Promise((resolve, reject) => {
mkdirp(customfontsDir, (err) => {
if (err) {
reject(err);
} else {
// write an empty file because we can't conditionally import inside gatsby-browser
fs.writeFile('./public/custom-fonts/index.css', '', (err) => {
if (err) {
reject(err);
}
resolve();
});
}
});
});
};
const loadCustomFonts = () => {
const fontNpmPackage = siteSettings.typography.npmPackage;
writeEmptyFile().then(() => {
if (fontNpmPackage) {
ncp.limit = 16;
mkdirp(customfontsDir, (err) => {
if (err) {
console.error('unable to create custom fonts folder');
throw err;
} else {
if (!performanceMode) {
ncp(`node_modules/${fontNpmPackage}`, customfontsDir, (err) => {
if (err) {
console.error('unable to copy font package');
throw err;
}
});
} else {
console.warn('Performance mode: external font will not be loaded!');
}
}
});
}
}).catch((err) => {
throw err;
});
};
// Ensure a clean copy of the custom fonts dir
if (fs.existsSync(customfontsDir)) {
rimraf(customfontsDir, {}, loadCustomFonts);
} else {
loadCustomFonts();
}
};
// Creates a `references` field that holds the references to other posts
exports.onCreateNode = async ({node, actions, getNodes}) => {
if (isNodeOfCollection(node, 'posts')) createReferencesField(node, actions, getNodes);
};
// Netlify cms fix for netlify deploys?
module.exports.resolvableExtensions = () => ['.json'];