-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgatsby-node.js
437 lines (378 loc) · 12.8 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
const path = require(`path`)
const fs = require("fs")
// const chunk = require(`lodash/chunk`)
const chunk = (arr, chunkSize = 1, cache = []) => {
const tmp = [...arr]
if (chunkSize <= 0) return cache
while (tmp.length) cache.push(tmp.splice(0, chunkSize))
return cache
}
// This is a simple debugging tool
// dd() will prettily dump to the terminal and kill the process
// const { dd } = require(`dumper.js`)
/**
* exports.createPages is a built-in Gatsby Node API.
* It's purpose is to allow you to create pages for your site! 💡
*
* See https://www.gatsbyjs.com/docs/node-apis/#createPages for more info.
*/
exports.createPages = async gatsbyUtilities => {
// Query our posts from the GraphQL server
const posts = await getPosts(gatsbyUtilities)
// If there are no posts in WordPress, don't do anything
if (!posts.length) {
return
}
// If there are posts, create pages for them
await createIndividualBlogPostPages({ posts, gatsbyUtilities })
// And a paginated archive for posts
await createBlogPostArchive({ posts, gatsbyUtilities })
const categories = await getCategories(gatsbyUtilities)
// If there are no pages in WordPress, don't do anything
if (!categories.length) {
return
}
let regEx = /\/services\//
let regEx1 = /\/industry\//
let filteredCat = categories
.filter(y => !y.uri.match(regEx))
.filter(y => !y.uri.match(regEx1))
// And a paginated archive for categoriezed posts
await createCategoriesArchive({ filteredCat, posts, gatsbyUtilities })
const pages = await getPages(gatsbyUtilities)
// If there are no pages in WordPress, don't do anything
if (!pages.length) {
return
}
// If there are pages, create pages for them
await createIndividualPages({ pages, gatsbyUtilities })
}
/**
* This function creates all the individual blog pages in this site
*/
const createIndividualBlogPostPages = async ({ posts, gatsbyUtilities }) =>
Promise.all(
posts.map(({ previous, post, next }) =>
// createPage is an action passed to createPages
// See https://www.gatsbyjs.com/docs/actions#createPage for more info
gatsbyUtilities.actions.createPage({
// Use the WordPress uri as the Gatsby page path
// This is a good idea so that internal links and menus work 👍
path: `${post.uri}`,
// use the blog post template as the page component
component: path.resolve(`./src/templates/blog-post.js`),
// `context` is available in the template as a prop and
// as a variable in GraphQL.
context: {
// we need to add the post id here
// so our blog post template knows which blog post
// the current page is (when you open it in a browser)
id: post.id,
// We also use the next and previous id's to query them and add links!
previousPostId: previous ? previous.id : null,
nextPostId: next ? next.id : null,
},
})
)
)
/**
* This function creates all the individual pages in this site
*/
const createIndividualPages = async ({ pages, gatsbyUtilities }) =>
Promise.all(
pages.map(({ page }) => {
let tempFile = fs.existsSync(`./src/templates/pages/${page.slug}.js`)
? `./src/templates/pages/${page.slug}.js`
: `./src/templates/page.js`
console.log(
`${page.title} / ${page.slug} page - template file: ${tempFile}`
)
page.slug !== "news" &&
// createPage is an action passed to createPages
// See https://www.gatsbyjs.com/docs/actions#createPage for more info
gatsbyUtilities.actions.createPage({
// Use the WordPress uri as the Gatsby page path
// This is a good idea so that internal links and menus work 👍
path: page.uri,
// use the blog post template as the page component
component: path.resolve(tempFile),
// `context` is available in the template as a prop and
// as a variable in GraphQL.
context: {
// we need to add the post id here
// so our blog post template knows which blog post
// the current page is (when you open it in a browser)
id: page.id,
},
})
})
)
/**
* This function creates archive pages for all blogs in this site
*/
async function createBlogPostArchive({ posts, gatsbyUtilities }) {
const graphqlResult = await gatsbyUtilities.graphql(/* GraphQL */ `
{
wp {
readingSettings {
postsPerPage
}
}
}
`)
const { postsPerPage } = graphqlResult.data.wp.readingSettings
const postsChunkedIntoArchivePages = chunk(posts, postsPerPage)
const totalPages = postsChunkedIntoArchivePages.length
return Promise.all(
postsChunkedIntoArchivePages.map(async (_posts, index) => {
const pageNumber = index + 1
const paginationArray = pagination(pageNumber, totalPages)
const getPagePath = page => {
if (page > 0 && page <= totalPages) {
// Since our news is our blog page
// we want the first page to be "/news/" and any additional pages
// to be numbered.
// "/news/2" for example
return page === 1 ? `/news` : `/news/${page}`
}
return null
}
// createPage is an action passed to createPages
// See https://www.gatsbyjs.com/docs/actions#createPage for more info
await gatsbyUtilities.actions.createPage({
path: getPagePath(pageNumber),
// use the blog post archive template as the page component
component: path.resolve(`./src/templates/blog-post-archive.js`),
// `context` is available in the template as a prop and
// as a variable in GraphQL.
context: {
// the index of our loop is the offset of which posts we want to display
// so for page 1, 0 * 10 = 0 offset, for page 2, 1 * 10 = 10 posts offset,
// etc
offset: index * postsPerPage,
// We need to tell the template how many posts to display too
postsPerPage,
totalPages,
currentPage: pageNumber,
currentPageBase: `/news/`,
nextPagePath: getPagePath(pageNumber + 1),
previousPagePath: getPagePath(pageNumber - 1),
paginationArray: paginationArray,
},
})
})
)
}
/**
* This function creates archive pages for each categories of blogs in this site
*/
async function createCategoriesArchive({
filteredCat,
posts,
gatsbyUtilities,
}) {
const graphqlResult = await gatsbyUtilities.graphql(/* GraphQL */ `
{
wp {
readingSettings {
postsPerPage
}
}
}
`)
const { postsPerPage } = graphqlResult.data.wp.readingSettings
filteredCat.map((cat, i) => {
let filteredPosts = posts.filter(post =>
post.post.categories.nodes.some(category => category.id === cat.id)
)
const postsChunkedIntoArchivePages = chunk(filteredPosts, postsPerPage)
const totalPages = postsChunkedIntoArchivePages.length
return Promise.all(
postsChunkedIntoArchivePages.map(async (_posts, index) => {
const pageNumber = index + 1
const paginationArray = pagination(pageNumber, totalPages)
const getPagePath = page => {
if (page > 0 && page <= totalPages) {
// Since our news is our blog page
// we want the first page to be "/news/" and any additional pages
// to be numbered.
// "/news/2" for example
return page === 1 ? `${cat.uri}` : `${cat.uri}${page}`
}
return null
}
// createPage is an action passed to createPages
// See https://www.gatsbyjs.com/docs/actions#createPage for more info
await gatsbyUtilities.actions.createPage({
path: getPagePath(pageNumber),
// use the blog post archive template as the page component
component: path.resolve(`./src/templates/blog-post-archive.js`),
// `context` is available in the template as a prop and
// as a variable in GraphQL.
context: {
// the index of our loop is the offset of which posts we want to display
// so for page 1, 0 * 10 = 0 offset, for page 2, 1 * 10 = 10 posts offset,
// etc
offset: index * postsPerPage,
// We need to tell the template how many posts to display too
postsPerPage,
totalPages,
currentPage: pageNumber,
currentPageBase: `${cat.uri}`,
nextPagePath: getPagePath(pageNumber + 1),
previousPagePath: getPagePath(pageNumber - 1),
paginationArray: paginationArray,
},
})
})
)
})
}
/**
* This function queries Gatsby's GraphQL server and asks for
* All WordPress blog posts. If there are any GraphQL error it throws an error
* Otherwise it will return the posts 🙌
*
* We're passing in the utilities we got from createPages.
* So see https://www.gatsbyjs.com/docs/node-apis/#createPages for more info!
*/
async function getPosts({ graphql, reporter }) {
const graphqlResult = await graphql(/* GraphQL */ `
query WpPosts {
# Query all WordPress blog posts sorted by date
allWpPost(sort: { fields: [date], order: DESC }) {
edges {
previous {
id
}
# note: this is a GraphQL alias. It renames "node" to "post" for this query
# We're doing this because this "node" is a post! It makes our code more readable further down the line.
post: node {
id
uri
categories {
nodes {
id
}
}
}
next {
id
}
}
}
}
`)
if (graphqlResult.errors) {
reporter.panicOnBuild(
`There was an error loading your blog posts`,
graphqlResult.errors
)
return
}
return graphqlResult.data.allWpPost.edges
}
/**
* This function queries Gatsby's GraphQL server and asks for
* All WordPress categories. If there are any GraphQL error it throws an error
* Otherwise it will return the categories 🙌
*
* We're passing in the utilities we got from createPages.
* So see https://www.gatsbyjs.com/docs/node-apis/#createPages for more info!
*/
async function getCategories({ graphql, reporter }) {
const graphqlResult = await graphql(/* GraphQL */ `
query WpCategory {
allWpCategory {
nodes {
id
name
uri
}
}
}
`)
if (graphqlResult.errors) {
reporter.panicOnBuild(
`There was an error loading your pages`,
graphqlResult.errors
)
return
}
return graphqlResult.data.allWpCategory.nodes
}
/**
* This function queries Gatsby's GraphQL server and asks for
* All WordPress pages. If there are any GraphQL error it throws an error
* Otherwise it will return the pages 🙌
*
* We're passing in the utilities we got from createPages.
* So see https://www.gatsbyjs.com/docs/node-apis/#createPages for more info!
*/
async function getPages({ graphql, reporter }) {
const graphqlResult = await graphql(/* GraphQL */ `
query WpPage {
# Query all WordPress blog posts sorted by date
allWpPage {
edges {
# note: this is a GraphQL alias. It renames "node" to "page" for this query
# We're doing this because this "node" is a page! It makes our code more readable further down the line.
page: node {
id
uri
slug
title
}
}
}
}
`)
if (graphqlResult.errors) {
reporter.panicOnBuild(
`There was an error loading your pages`,
graphqlResult.errors
)
return
}
return graphqlResult.data.allWpPage.edges
}
const getRange = (start, end) => {
return Array(end - start + 1)
.fill()
.map((v, i) => i + start)
}
const pagination = (currentPage, pageCount) => {
let delta
if (pageCount <= 7) {
// delta === 7: [1 2 3 4 5 6 7]
delta = 7
} else {
// delta === 2: [1 ... 4 5 6 ... 10]
// delta === 4: [1 2 3 4 5 ... 10]
delta = currentPage > 4 && currentPage < pageCount - 3 ? 2 : 4
}
const range = {
start: Math.round(currentPage - delta / 2),
end: Math.round(currentPage + delta / 2),
}
if (range.start - 1 === 1 || range.end + 1 === pageCount) {
range.start += 1
range.end += 1
}
let pages =
currentPage > delta
? getRange(
Math.min(range.start, pageCount - delta),
Math.min(range.end, pageCount)
)
: getRange(1, Math.min(pageCount, delta + 1))
const withDots = (value, pair) =>
pages.length + 1 !== pageCount ? pair : [value]
if (pages[0] !== 1) {
pages = withDots(1, [1, "..."]).concat(pages)
}
if (pages[pages.length - 1] < pageCount) {
pages = pages.concat(withDots(pageCount, ["...", pageCount]))
}
return pages
}