-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgatsby-node.ts
94 lines (84 loc) · 2.53 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
import path from "path";
import fetch from "isomorphic-fetch";
import { CreateNodeArgs, CreatePagesArgs, SourceNodesArgs, CreateSchemaCustomizationArgs } from "gatsby";
import { CreatePostPagesQuery, Maybe, MdxFields } from "./gatsby-graphql";
import { createFilePath } from "gatsby-source-filesystem";
const fetchGithubReposAndTurnToNodes = async (args: SourceNodesArgs) => {
const { actions, createNodeId, createContentDigest } = args;
const res = await fetch("https://api.github.com/users/melboudali/repos?sort=%22created%22");
const repos = await res.json();
for (const repo of repos) {
const nodeMeta = {
id: createNodeId(`repo-${repo.name}`),
parent: null,
children: [],
internal: {
type: "Repo",
mediaType: "application/json",
contentDigest: createContentDigest(repo),
},
};
actions.createNode({
...repo,
...nodeMeta,
});
}
};
exports.onCreateNode = (args: CreateNodeArgs): void => {
// Create a slug field for markdown post nodes.
const { actions, node, getNode } = args;
const { createNodeField } = actions;
if (node.internal.type === "Mdx") {
const slug = createFilePath({ node, getNode });
createNodeField({
node,
name: "slug",
value: `/blog${slug}`,
});
}
};
interface resType {
data?: CreatePostPagesQuery;
}
interface postType {
fields?: Maybe<Pick<MdxFields, "slug">>;
}
const turnPostsIntoPages = async (args: CreatePagesArgs) => {
const { actions, graphql } = args;
const postTemplate = path.resolve("./src/templates/Post.tsx");
const res: resType = await graphql(`
query createPostPages {
posts: allMdx {
nodes {
fields {
slug
}
}
}
}
`);
res.data?.posts.nodes.forEach((post: postType) => {
actions.createPage({
path: post.fields?.slug!,
component: postTemplate,
context: { slug: post.fields?.slug! },
});
});
};
exports.createSchemaCustomization = (args: CreateSchemaCustomizationArgs) => {
const { actions } = args;
actions.createTypes(`
type Mdx implements Node {
frontmatter: MdxFrontmatter!
}
type MdxFrontmatter {
tags: [String]
}
`);
};
exports.sourceNodes = async (params: SourceNodesArgs): Promise<void> => {
await Promise.all([fetchGithubReposAndTurnToNodes(params)]);
};
exports.createPages = async (params: CreatePagesArgs) => {
await Promise.all([turnPostsIntoPages(params)]);
};