-
Notifications
You must be signed in to change notification settings - Fork 1
/
gatsby-node.js
111 lines (97 loc) · 2.92 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
const _ = require('lodash')
const path = require('path')
const { createFilePath } = require('gatsby-source-filesystem')
const { fmImagesToRelative } = require('gatsby-remark-relative-images')
exports.createPages = ({ actions, graphql }) => {
const { createPage } = actions
return graphql(`
{
allMarkdownRemark(limit: 1000) {
edges {
node {
id
frontmatter {
template
title
}
fields {
slug
contentType
}
}
}
}
}
`).then(result => {
if (result.errors) {
result.errors.forEach(e => console.error(e.toString()))
return Promise.reject(result.errors)
}
const mdFiles = result.data.allMarkdownRemark.edges
const contentTypes = _.groupBy(mdFiles, 'node.fields.contentType')
_.each(contentTypes, (pages, contentType) => {
const pagesToCreate = pages.filter(page =>
// get pages with template field
_.get(page, `node.frontmatter.template`)
)
if (!pagesToCreate.length) return console.log(`Skipping ${contentType}`)
console.log(`Creating ${pagesToCreate.length} ${contentType}`)
pagesToCreate.forEach((page, index) => {
const id = page.node.id
createPage({
// page slug set in md frontmatter
path: page.node.fields.slug,
component: path.resolve(
`src/templates/${String(page.node.frontmatter.template)}.js`
),
// additional data can be passed via context
context: {
id
}
})
})
})
})
}
exports.onCreateNode = ({ node, actions, getNode }) => {
const { createNodeField } = actions
// convert frontmatter images
fmImagesToRelative(node)
// Create smart slugs
// https://github.com/Vagr9K/gatsby-advanced-starter/blob/master/gatsby-node.js
let slug
if (node.internal.type === 'MarkdownRemark') {
const fileNode = getNode(node.parent)
const parsedFilePath = path.parse(fileNode.relativePath)
if (_.get(node, 'frontmatter.slug')) {
slug = `/${node.frontmatter.slug.toLowerCase()}/`
} else if (
// home page gets root slug
parsedFilePath.name === 'home' &&
parsedFilePath.dir === 'pages'
) {
slug = `/`
} else if (_.get(node, 'frontmatter.title')) {
slug = `/${_.kebabCase(parsedFilePath.dir)}/${_.kebabCase(
node.frontmatter.title
)}/`
} else if (parsedFilePath.dir === '') {
slug = `/${parsedFilePath.name}/`
} else {
slug = `/${parsedFilePath.dir}/`
}
createNodeField({
node,
name: 'slug',
value: slug
})
// Add contentType to node.fields
createNodeField({
node,
name: 'contentType',
value: parsedFilePath.dir
})
}
}
// Random fix for https://github.com/gatsbyjs/gatsby/issues/5700
module.exports.resolvableExtensions = () => ['.json']