-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
gatsby-node.js
126 lines (106 loc) · 2.47 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
const fs = require('fs')
const path = require('path')
exports.onPreBootstrap = ({ reporter }, options) => {
const contentPath = options.contentPath || 'content'
const blogPath = options.blogPath || 'blog'
const directories = [contentPath, path.join(contentPath, blogPath)]
directories.forEach((directory) => {
if (!fs.existsSync(directory)) {
reporter.info(`Creating ${directory} folder.`)
fs.mkdirSync(directory)
}
})
}
function findDepthOfFileOrDir(node) {
const { absolutePath } = node
const absPath = absolutePath.split('/content')[1]
const pathArr = absPath.split('/').filter((item) => item)
return pathArr.length
}
exports.createSchemaCustomization = ({ actions, schema }) => {
const { createTypes } = actions
const blogTypes = `
type Mdx implements Node {
fields: Fields
}
type Fields {
postType: String
}
`
const directoryTypes = `
type Directory implements Node {
fields: Fields
}
type Fields {
depth: String!
}
`
const FileTypes = `
type File implements Node {
fields: Fields
}
type Fields {
depth: String!
}
`
createTypes(blogTypes)
createTypes(directoryTypes)
createTypes(FileTypes)
}
exports.onCreateNode = ({ actions, node, getNode }) => {
const { createNodeField } = actions
const {
internal: { type },
} = node
if (type === 'Directory' || type === 'File') {
const depth = findDepthOfFileOrDir(node)
createNodeField({
node,
name: 'depth',
value: depth,
type: 'string',
})
}
if (type === 'Mdx') {
const { sourceInstanceName } = getNode(node.parent)
createNodeField({
node,
name: 'postType',
value: sourceInstanceName,
type: 'string',
})
}
}
exports.createPages = async ({ actions, graphql, reporter }, options) => {
const { createPage } = actions
const result = await graphql(`
query {
allMdx {
nodes {
id
slug
fields {
postType
}
}
}
}
`)
if (result.errors) {
reporter.panic('Error loading blogs', result.errors)
return
}
const posts = result.data.allMdx.nodes.filter(
(node) => node.fields.postType === 'blog'
)
posts.forEach((node) => {
const { id, slug } = node
createPage({
path: `/blog/${slug}`,
component: require.resolve('./src/components/blog/singlePost.tsx'),
context: {
id: id,
},
})
})
}