-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgatsby-node.ts
108 lines (94 loc) · 2.72 KB
/
gatsby-node.ts
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
import type { GatsbyNode } from 'gatsby'
import { createFilePath } from 'gatsby-source-filesystem'
import { resolve } from 'path'
export const createSchemaCustomization: GatsbyNode['createSchemaCustomization'] = ({ actions }) => {
actions.createTypes(`
type Site {
siteMetadata: SiteMetadata!
}
type SiteMetadata {
description: String!
siteUrl: String!
title: String!
}
type MarkdownRemarkFrontmatter {
category: String!
date: Date!
description: String!
draft: Boolean!
layout: String!
title: String!
}
type MarkdownRemarkFields {
slug: String!
}
type MarkdownRemark implements Node {
frontmatter: MarkdownRemarkFrontmatter!
fields: MarkdownRemarkFields!
}
`)
}
export const onCreateNode: GatsbyNode['onCreateNode'] = ({ node, actions, getNode }) => {
const { createNodeField } = actions
if (node.internal.type === 'MarkdownRemark') {
if (!node.parent) {
throw new Error('[UNREACHABLE]: MarkdownRemark does not have a parent node.')
}
const fileNode = getNode(node.parent)
if (!fileNode) {
throw new Error('[UNREACHABLE]: A parent node does not exists.')
}
const parsedFilePath = createFilePath({ node: fileNode, getNode, basePath: 'posts' })
const slug = `${parsedFilePath.split('---')[1].replace(/\/$/, '')}`
createNodeField({
node,
name: 'slug',
value: slug,
})
} else if (node.internal.type === 'File') {
const parsedFilePath = createFilePath({ node, getNode, basePath: 'posts' })
const slug = `${parsedFilePath.split('---')[1].replace(/\/$/, '')}`
createNodeField({
node,
name: 'slug',
value: slug,
})
}
}
export const createPages: GatsbyNode['createPages'] = async ({ actions, graphql }) => {
const { createPage } = actions
const allMarkdown = await graphql<{ allMarkdownRemark: Queries.MarkdownRemarkConnection }>(`
{
allMarkdownRemark(limit: 1000, filter: { frontmatter: { draft: { ne: true } } }) {
edges {
node {
fields {
slug
}
frontmatter {
category
layout
}
}
}
}
}
`)
if (allMarkdown.errors) {
console.error(allMarkdown.errors)
throw allMarkdown.errors
}
allMarkdown.data?.allMarkdownRemark.edges.forEach(edge => {
if (edge.node.frontmatter?.layout === 'post') {
if (!edge.node.fields || !edge.node.fields.slug) {
return
}
const slug = edge.node.fields.slug
createPage({
path: `/posts/${slug}`,
component: resolve('./src/templates/post-template.tsx'),
context: { slug },
})
}
})
}