~samhh/samhh.com

ref: 9308fd818fa00d0e281ae60d3f723cb1928cfa80 samhh.com/gatsby-node.ts -rw-r--r-- 1.6 KiB
9308fd81 — Sam A. Horvath-Hunt Add Unsplash job 1 year, 3 months ago
                                                                                
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
/* eslint-disable functional/no-conditional-statement, functional/no-expression-statement */

import { GatsbyNode } from "gatsby"
import { createFilePath } from "gatsby-source-filesystem"

// Until it's the default behaviour:
// https://github.com/gatsbyjs/gatsby/issues/28657
export const onCreateBabelConfig: GatsbyNode["onCreateBabelConfig"] = ({
  actions,
}) =>
  actions.setBabelPlugin({
    name: "@babel/plugin-transform-react-jsx",
    options: {
      runtime: "automatic",
    },
  })

export const onCreateNode: GatsbyNode["onCreateNode"] = ({
  node,
  getNode,
  actions: { createNodeField },
}) => {
  if (node.internal.type !== "MarkdownRemark") return

  const slug = createFilePath({ node, getNode, basePath: "pages" })
  createNodeField({ node, name: "slug", value: slug })
}

export const createPages: GatsbyNode["createPages"] = async ({
  actions: { createPage },
  graphql,
  reporter,
}) => {
  const template = require.resolve("./src/templates/blog-post.tsx")

  type Res = {
    allMarkdownRemark: { edges: { node: { frontmatter: { slug: string } } }[] }
  }
  const res = await graphql<Res>(`
    {
      allMarkdownRemark {
        edges {
          node {
            frontmatter {
              slug
            }
          }
        }
      }
    }
  `)

  if (res.errors) {
    reporter.panicOnBuild("Error while running GraphQL query.")
    return
  }

  // eslint-disable-next-line functional/no-loop-statement
  for (const {
    node: {
      frontmatter: { slug },
    },
  } of res.data?.allMarkdownRemark?.edges ?? []) {
    createPage({
      path: `/blog/${slug}/`,
      component: template,
      context: { slug },
    })
  }
}