|
| 1 | +/** |
| 2 | + * MIT LICENSE *** |
| 3 | + * ------------------------------------------------------------------------- |
| 4 | + * This code may be modified and distributed under the MIT license. |
| 5 | + * See the LICENSE file for details. |
| 6 | + * ------------------------------------------------------------------------- |
| 7 | + * @summary Create pages via Gatsby Node API |
| 8 | + * @author Alvis HT Tang <alvis@hilbert.space> |
| 9 | + * @license MIT |
| 10 | + * @copyright Copyright (c) 2022 - All Rights Reserved. |
| 11 | + * ------------------------------------------------------------------------- |
| 12 | + */ |
| 13 | + |
| 14 | +import { resolve } from 'node:path'; |
| 15 | + |
| 16 | +import type { Actions, CreatePagesArgs, GatsbyNode } from 'gatsby'; |
| 17 | + |
| 18 | +export const createPages: GatsbyNode['createPages'] = async ({ |
| 19 | + actions: { createPage }, |
| 20 | + graphql, |
| 21 | +}) => { |
| 22 | + createProjectPages(await queryProjects(graphql), createPage); |
| 23 | +}; |
| 24 | + |
| 25 | +/** |
| 26 | + * create project pages |
| 27 | + * @param projects projects metadata |
| 28 | + * @param createPage the createPage function |
| 29 | + */ |
| 30 | +function createProjectPages( |
| 31 | + projects: Queries.ProjectsQuery | undefined, |
| 32 | + createPage: Actions['createPage'], |
| 33 | +): void { |
| 34 | + projects?.notionDatabase?.childrenNotionPage?.forEach((page) => { |
| 35 | + const mdx = page?.childMarkdownRemark; |
| 36 | + const path = page?.properties?.path; |
| 37 | + |
| 38 | + if (mdx && path) { |
| 39 | + createPage({ |
| 40 | + path, |
| 41 | + // NOTE: must resolve to the absolute path of the component |
| 42 | + component: resolve(__dirname, 'src', 'templates', 'project.tsx'), |
| 43 | + context: { id: mdx.id }, |
| 44 | + }); |
| 45 | + } |
| 46 | + }); |
| 47 | +} |
| 48 | + |
| 49 | +/** |
| 50 | + * get projects metadata |
| 51 | + * @param graphql the graphql query function |
| 52 | + * @returns projects metadata |
| 53 | + */ |
| 54 | +async function queryProjects( |
| 55 | + graphql: CreatePagesArgs['graphql'], |
| 56 | +): Promise<Queries.ProjectsQuery | undefined> { |
| 57 | + const { data } = await graphql<Queries.ProjectsQuery>(` |
| 58 | + query Projects { |
| 59 | + notionDatabase(title: { eq: "Projects" }) { |
| 60 | + childrenNotionPage { |
| 61 | + childMarkdownRemark { |
| 62 | + id |
| 63 | + } |
| 64 | + properties { |
| 65 | + path |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + `); |
| 71 | + |
| 72 | + return data; |
| 73 | +} |
0 commit comments