Skip to content

Instantly share code, notes, and snippets.

@kmelve
Created January 24, 2020 17:33
Show Gist options
  • Save kmelve/b89ec52cf0a86d6f1c1b98e91fc433df to your computer and use it in GitHub Desktop.
Save kmelve/b89ec52cf0a86d6f1c1b98e91fc433df to your computer and use it in GitHub Desktop.
const { isFuture, parseISO } = require('date-fns')
/**
* Implement Gatsby's Node APIs in this file.
*
* See: https://www.gatsbyjs.org/docs/node-apis/
*/
const { format } = require('date-fns')
async function createBlogPostPages (graphql, actions, reporter) {
const { createPage } = actions
const result = await graphql(`
{
allSanityPost(
filter: { slug: { current: { ne: null } }, publishedAt: { ne: null } }
) {
edges {
node {
id
publishedAt
slug {
current
}
}
}
}
}
`)
if (result.errors) throw result.errors
const postEdges = (result.data.allSanityPost || {}).edges || []
postEdges
.filter(edge => !isFuture(parseISO(edge.node.publishedAt)))
.forEach((edge, index) => {
const { id, slug = {}, publishedAt } = edge.node
const dateSegment = format(parseISO(publishedAt), 'yyyy/MM')
const path = `/blog/${dateSegment}/${slug.current}/`
reporter.info(`Creating blog post page: ${path}`)
createPage({
path,
component: require.resolve('./src/templates/blog-post.js'),
context: { id, permalink: `https://www.knutmelvaer.no${path}` }
})
})
}
exports.createPages = async ({ graphql, actions, reporter }) => {
await createBlogPostPages(graphql, actions, reporter)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment