-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgatsby-node.ts
More file actions
87 lines (78 loc) · 2.67 KB
/
gatsby-node.ts
File metadata and controls
87 lines (78 loc) · 2.67 KB
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
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { GatsbyNode } from 'gatsby'
import path from 'path'
// graphql function doesn't throw an error so we have to check to check for the result.errors to throw manually
const wrapper = (promise: any) =>
promise.then((result: any) => {
if (result.errors) {
throw result.errors
}
return result
})
export const onCreateNode: GatsbyNode['onCreateNode'] = ({ node, actions }: any) => {
const { createNodeField } = actions
let slug
// Search for MDX filenodes
if (node.internal.type === 'Mdx') {
if (
Object.prototype.hasOwnProperty.call(node, 'frontmatter') &&
Object.prototype.hasOwnProperty.call(node.frontmatter, 'slug')
) {
// If the frontmatter has a "slug", use it
slug = `/${convertToKebabCase(node.frontmatter.slug)}`
} else if (
Object.prototype.hasOwnProperty.call(node, 'frontmatter') &&
Object.prototype.hasOwnProperty.call(node.frontmatter, 'title')
) {
// If not derive a slug from the "title" in the frontmatter
slug = `/${convertToKebabCase(node.frontmatter.title)}`
}
createNodeField({ node, name: 'slug', value: slug })
}
}
export const createPages: GatsbyNode<Queries.ProjectNodesQuery>['createPages'] = async ({ graphql, actions }) => {
const { createPage } = actions
const projectTemplate = path.resolve('./src/templates/project.tsx')
const result: { data: Queries.ProjectNodesQuery } = await wrapper(
graphql(`
query ProjectNodes {
projects: allMdx(sort: { frontmatter: { date: DESC } }) {
edges {
node {
internal {
contentFilePath
}
fields {
slug
}
frontmatter {
title
}
}
}
}
}
`)
)
const projectPosts = result.data.projects.edges
projectPosts.forEach((edge, index) => {
const next = index === 0 ? null : projectPosts[index - 1].node
const prev = index === projectPosts.length - 1 ? null : projectPosts[index + 1].node
createPage({
path: edge.node.fields.slug,
component: `${projectTemplate}?__contentFilePath=${edge.node.internal.contentFilePath}`,
context: {
slug: edge.node.fields.slug,
// Pass the current directory of the project as regex in context so that the GraphQL query can filter by it
absolutePathRegex: `/^${path.dirname(edge.node.internal.contentFilePath)}/`,
prev,
next
}
})
})
}
const convertToKebabCase = (text: string) =>
text
.replace(/([a-z])([A-Z])/g, '$1-$2')
.replace(/[\s_]+/g, '-')
.toLowerCase()