-
Notifications
You must be signed in to change notification settings - Fork 2
/
gatsby-node.ts
376 lines (351 loc) · 10.3 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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
import { GatsbyNode } from 'gatsby';
import path from 'path';
import type { NoteTemplatePageContext } from './src/templates/NoteTemplate';
import type { FeedTemplatePageContext } from './src/templates/FeedTemplate';
import { execSync } from 'child_process';
import { slugify } from './src/gatsby/slugify';
import { FileSystemNode } from 'gatsby-source-filesystem';
import { getSrc, IGatsbyImageData } from 'gatsby-plugin-image';
type GatsbyNodeQuery = {
site: {
siteMetadata?: {
garden?: {
basePath?: string;
};
feed?: {
basePath?: string;
useIndex?: boolean;
notesPerPage?: number;
};
};
};
allMarkdownRemark: {
edges: Array<{
node: {
id: string;
html: string;
headings: Array<{ depth: number; id: string; value: string }>;
fields?: { slug?: string; title?: string };
frontmatter?: {
cover_image: {
childImageSharp?: { gatsbyImageData: IGatsbyImageData };
};
};
excerpt?: string;
outboundReferences: Array<{
id: string;
fields?: { slug?: string; title?: string };
}>;
inboundReferences: Array<{
id: string;
fields?: { slug?: string; title?: string };
}>;
};
}>;
};
};
export const createPages: GatsbyNode['createPages'] = async ({
graphql,
actions,
reporter,
}) => {
const { createPage, createRedirect } = actions;
const result = await graphql<GatsbyNodeQuery>(
`
{
site {
siteMetadata {
garden {
basePath
}
feed {
basePath
useIndex
notesPerPage
}
}
}
allMarkdownRemark(
filter: { frontmatter: { published: { eq: true } } }
sort: { fields: [fields___gitAuthorTime], order: [DESC] }
) {
edges {
node {
id
html
headings {
id
depth
value
}
fields {
slug
title
}
frontmatter {
cover_image {
childImageSharp {
gatsbyImageData(height: 630, width: 1200, layout: FIXED)
}
}
}
excerpt(truncate: true, pruneLength: 160)
outboundReferences {
... on MarkdownRemark {
id
fields {
slug
title
}
}
}
inboundReferences {
... on MarkdownRemark {
id
fields {
slug
title
}
}
}
}
}
}
}
`,
);
if (result.errors) {
reporter.panicOnBuild(`Error while running GraphQL query.`);
return;
}
// extract query result
const { feed, garden } = result.data?.site?.siteMetadata || {};
const notes = result.data?.allMarkdownRemark?.edges || [];
// create garden
const { basePath: gardenBasePath = '/garden' } = garden || {};
const noteTemplate = path.resolve('./src/templates/NoteTemplate.tsx');
notes.forEach(({ node }) => {
const {
id,
html,
headings,
inboundReferences,
outboundReferences,
excerpt,
} = node;
const { slug, title = 'Note' } = node.fields || {};
const { gatsbyImageData } =
node.frontmatter?.cover_image.childImageSharp || {};
if (slug) {
const urlPath = `${gardenBasePath}/${slug}`;
console.log(urlPath);
createPage<NoteTemplatePageContext>({
path: urlPath,
component: noteTemplate,
context: {
id,
html,
headings,
inboundReferences: inboundReferences.map((r) => ({
title: r.fields?.title || '',
url: `${gardenBasePath}/${r.fields?.slug}`,
})),
outboundReferences: outboundReferences.map((r) => ({
title: r.fields?.title || '',
url: `${gardenBasePath}/${r.fields?.slug}`,
})),
title,
metaImage: gatsbyImageData && getSrc(gatsbyImageData),
metaDescription: excerpt,
},
});
}
});
// create feed
const {
notesPerPage = 10,
basePath: feedBasePath = `/page`,
useIndex: useIndexAsFeed = true,
} = feed || {};
const feedTempate = path.resolve('./src/templates/FeedTemplate/index.tsx');
const feedRootPath = useIndexAsFeed ? '/' : feedBasePath;
const numPages = Math.ceil(notes.length / notesPerPage);
createRedirect({
fromPath: `${feedBasePath}/1`,
toPath: feedRootPath,
});
Array.from({ length: numPages }).forEach((_, i) => {
const page = i + 1;
createPage<FeedTemplatePageContext>({
path: page === 1 ? feedRootPath : `${feedBasePath}/${page}`,
component: feedTempate,
context: {
limit: notesPerPage,
skip: i * notesPerPage,
numPages,
currentPage: page,
feedBasePath,
feedRootPath,
gardenBasePath: gardenBasePath,
},
});
});
};
export const onCreateWebpackConfig: GatsbyNode['onCreateWebpackConfig'] = ({
actions,
}) => {
actions.setWebpackConfig({
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'),
'@components': path.resolve(__dirname, 'src/components'),
'@pages': path.resolve(__dirname, 'src/pages'),
'@images': path.resolve(__dirname, 'src/images'),
'@icons': path.resolve(__dirname, 'src/icons'),
},
},
});
};
export const createSchemaCustomization: GatsbyNode['createSchemaCustomization'] =
({ actions, schema }) => {
const { createTypes } = actions;
const contributorsTypeDefs = `
type ContributorsJson implements Node @dontInfer {
name: String!
position: String
imageUrl: String
contactInfo: ContributorsJsonContactInfo
shortIntro: String
}
type ContributorsJsonContactInfo {
website: String
email: String
github: String
twitter: String
facebook: String
}
`;
createTypes(contributorsTypeDefs);
const frontmatterTypeDefs = [
`
type MarkdownRemark implements Node {
frontmatter: Frontmatter
}
type Frontmatter {
published: Boolean
featured: Boolean
}
`,
// test_image: File @link(by: "name")
// Custom resolver needed because `contributors: [ContributorsJson] @link(by: "name")` does not support default value
schema.buildObjectType({
name: 'Frontmatter',
fields: {
cover_image: {
type: 'File!',
resolve: async (source, _args, context) => {
const { cover_image } = source;
if (cover_image) {
const result = await context.nodeModel.findOne({
type: 'File',
query: {
filter: {
base: { eq: cover_image },
sourceInstanceName: { eq: 'garden' },
},
},
});
if (result) return result;
}
return await context.nodeModel.findOne({
type: 'File',
query: {
filter: {
base: { eq: 'card-default.png' },
sourceInstanceName: { eq: 'images' },
},
},
});
},
},
},
}),
schema.buildObjectType({
name: 'Frontmatter',
fields: {
contributors: {
type: '[ContributorsJson!]',
resolve: (source, _args, context) => {
const { contributors } = source;
if (!contributors) return null;
return contributors.map(async (contributorName: string) => {
const result = await context.nodeModel.findOne({
type: 'ContributorsJson',
query: {
filter: { name: { eq: contributorName } },
},
});
return result || { name: contributorName };
});
},
},
},
}),
];
createTypes(frontmatterTypeDefs);
};
export const onCreateNode: GatsbyNode['onCreateNode'] = async ({
node,
actions,
getNode,
// store,
// cache,
// createNodeId,
// reporter,
}) => {
const { createNodeField } = actions;
if (node.internal.type === 'MarkdownRemark' && node.parent) {
// git author time
const command = `git -C src/garden log -1 --pretty=format:%aI "${node.fileAbsolutePath}"`;
const gitAuthorTime = execSync(command).toString();
console.log(`${node.fileAbsolutePath}:`, gitAuthorTime);
actions.createNodeField({
node,
name: 'gitAuthorTime',
value: gitAuthorTime,
});
// slug and title
const parentNode = getNode(node.parent);
if (parentNode && parentNode.internal.type === `File`) {
const fileNode = parentNode as FileSystemNode;
// const relativeDir = fileNode.relativeDirectory;
// const relativePath = fileNode.relativePath;
const fileName = fileNode.name;
const slug = slugify(fileName);
createNodeField({
name: `slug`,
node,
value: slug,
});
createNodeField({ name: `title`, node, value: fileName });
}
}
// if (node.internal.type === 'MarkdownRemark') {
// const frontmatter = node.frontmatter as any;
// if (frontmatter.test_image) {
// const fileNode = await createRemoteFileNode({
// url: frontmatter.test_image, // string that points to the URL of the image
// parentNodeId: node.id, // id of the parent node of the fileNode you are going to create
// createNode, // helper function in gatsby-node to generate the node
// createNodeId, // helper function in gatsby-node to generate the node id
// cache,
// store,
// reporter,
// });
// // if the file was created, extend the node with "localFile"
// if (fileNode) {
// createNodeField({ node, name: 'localFile', value: fileNode.id });
// }
// }
// }
};