/
gatsby-node.js
93 lines (83 loc) · 2.1 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
/**
* Implement Gatsby's Node APIs in this file.
*
* See: https://www.gatsbyjs.org/docs/node-apis/
*/
const kebabCase = require('lodash.kebabcase');
const path = require('path');
exports.onCreateNode = (
{ node, boundActionCreators, getNode } /* : NodeParams */
) => {
const { createNodeField } = boundActionCreators;
if (node.internal.type === 'MarkdownRemark') {
const fileNode = getNode(node.parent);
const parsedFilePath = path.parse(fileNode.relativePath);
let section = parsedFilePath.dir;
let slug;
if (
parsedFilePath.name.match(/Readme/i)
&& fileNode.dir.match(/\/fields\/types\//)
) {
section = 'api/field'; // fake the path for slug consistency
slug = `/${section}/${kebabify(parsedFilePath.dir)}`;
} else {
if (parsedFilePath.name === 'index') {
slug = `/${kebabify(parsedFilePath.dir)}`;
} else {
slug = `/${kebabify(parsedFilePath.dir)}/${kebabify(
parsedFilePath.name
)}`;
}
}
// If file isn't in subdirectory "dir" will be empty.
slug = slug.replace('//', '/');
createNodeField({ node, name: 'slug', value: slug });
createNodeField({ node, name: 'section', value: section });
}
};
exports.createPages = (
{ graphql, boundActionCreators } /* : NodeParams */
) /* : Promise<any> */ => {
const { createPage } = boundActionCreators;
return new Promise((resolve, reject) => {
const articleComponent = path.resolve('templates/template-doc-layout.js');
resolve(
graphql(
`
{
allMarkdownRemark(limit: 1000) {
edges {
node {
fields {
slug
}
}
}
}
}
`
).then(result => {
if (result.errors) {
/* eslint-disable-next-line no-console */
console.log(result.errors);
reject(result.errors);
}
result.data.allMarkdownRemark.edges.forEach(edge => {
createPage({
path: edge.node.fields.slug, // required
component: articleComponent,
context: {
slug: edge.node.fields.slug,
},
});
});
})
);
});
};
function kebabify (string) {
return string
.split('/')
.map(s => kebabCase(s))
.join('/');
}