-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgatsby-node.js
101 lines (91 loc) · 2.57 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
/**
* Implement Gatsby's Node APIs in this file.
*
* See: https://www.gatsbyjs.org/docs/node-apis/
*/
// You can delete this file if you're not using it
const { createFilePath } = require(`gatsby-source-filesystem`)
exports.onCreateNode = ({ node, actions, getNode }) => {
const { createNodeField } = actions
if (node.internal.type === `MarkdownRemark`) {
const value = createFilePath({ node, getNode })
const [month, day, year] = new Date(node.frontmatter.date)
.toLocaleDateString('en-EN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
})
.split('/')
const slug = value.replace('/posts/', '').replace(/\/$/, '')
const url = `${slug}`
createNodeField({
name: `slug`,
node,
value: url,
})
}
}
const path = require(`path`)
// 1. This is called once the data layer is bootstrapped to let plugins create pages from data.
exports.createPages = ({ graphql, actions }) => {
// 1.1 Getting the method to create pages
const { createPage } = actions
// 1.2 Tell which layout Gatsby should use to thse pages
const blogLayout = path.resolve(`./src/components/blogPost.js`)
const blogListLayout = path.resolve(`./src/pages/index.js`)
// 2 Return the method with the query
return graphql(`
query blogPosts {
allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) {
edges {
node {
fields {
slug
}
frontmatter {
title
date
description
keywords
}
html
}
}
}
}
`).then(result => {
// 2.1 Handle the errors
if (result.errors) {
console.error(result.errors)
// reject(result.errors)
}
// 2.2 Our posts are here
const posts = result.data.allMarkdownRemark.edges
const postsPerPage = 5
const numPages = Math.ceil(posts.length / postsPerPage)
// Creating blog list with pagination
Array.from({ length: numPages }).forEach((_, i) => {
createPage({
path: i === 0 ? `/` : `/page/${i + 1}`,
component: blogListLayout,
context: {
limit: postsPerPage,
skip: i * postsPerPage,
currentPage: i + 1,
numPages,
},
})
})
// 3 Loop throught all posts
posts.forEach((post, index) => {
// 3.1 Finally create posts
createPage({
path: post.node.fields.slug,
component: blogLayout,
context: {
slug: post.node.fields.slug,
},
})
})
})
}