namesny-com/gatsby-node.js

93 lines
2.2 KiB
JavaScript
Raw Normal View History

const path = require(`path`)
const { createFilePath } = require(`gatsby-source-filesystem`)
2020-09-16 18:40:52 +00:00
exports.onCreateNode = ({ node, getNode, actions }) => {
const { createNodeField } = actions
if (node.internal.type === `MarkdownRemark`) {
const slug = createFilePath({ node, getNode, basePath: `pages` })
2020-10-05 16:36:54 +00:00
const parent = getNode(node.parent)
createNodeField({
node,
name: `slug`,
value: slug,
})
2020-10-05 16:36:54 +00:00
createNodeField({
node,
name: 'collection',
value: parent.sourceInstanceName,
})
}
}
exports.createPages = async ({ graphql, actions, reporter }) => {
const { createPage } = actions
2020-10-06 18:51:49 +00:00
// Posts query
const posts = await graphql(
`
{
2020-10-05 16:36:54 +00:00
allMarkdownRemark(filter:{frontmatter: {draft: {ne: true}}, fields: {collection: {eq: "posts"}}}) {
edges {
node {
fields {
slug
}
}
}
}
}
`
)
// Handle errors
2020-10-06 18:51:49 +00:00
if (posts.errors) {
reporter.panicOnBuild(`Error while running GraphQL query.`)
return
}
// Create pages for each markdown file.
const blogPostTemplate = path.resolve(`src/templates/blog-post.js`)
2020-10-06 18:51:49 +00:00
posts.data.allMarkdownRemark.edges.forEach(({ node }) => {
createPage({
path: `/posts${node.fields.slug}`,
component: blogPostTemplate,
2020-10-06 18:51:49 +00:00
context: {
slug: node.fields.slug,
},
})
})
const pages = await graphql(
`
{
allMarkdownRemark(filter: {fields: {collection: {eq: "pages"}}}) {
edges {
node {
fields {
slug
}
}
}
}
}
`
)
// Handle errors
if (pages.errors) {
reporter.panicOnBuild(`Error while running GraphQL query.`)
return
}
// Create pages for each markdown file.
const pageTemplate = path.resolve(`src/templates/page.js`)
pages.data.allMarkdownRemark.edges.forEach(({ node }) => {
createPage({
path: node.fields.slug,
component: pageTemplate,
context: {
slug: node.fields.slug,
},
})
})
}