Skip to content

Instantly share code, notes, and snippets.

@kmelve
Last active May 23, 2019 10:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmelve/beee0a58a86aa8830b72d43de5e85582 to your computer and use it in GitHub Desktop.
Save kmelve/beee0a58a86aa8830b72d43de5e85582 to your computer and use it in GitHub Desktop.
Dated publishing in Gatsby and Sanity.io
const { isFuture, format } = require('date-fns')
async function createBlogPostPages(graphql, actions, reporter) {
const { createPage, createPageDependency } = actions
const result = await graphql(`
{
allSanityPost {
edges {
node {
id
slug {
current
}
publishedAt
}
}
}
}
`)
if (result.errors) throw result.errors
const postEdges = (result.data.allSanityPost || {}).edges || []
postEdges
.filter(({publishedAt}) => !isFuture(publishedAt))
.forEach((edge, index) => {
const { id, slug = {}, publishedAt } = edge.node
const dateSegment = format(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 },
})
createPageDependency({ path, nodeId: id })
})
}
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