Last active
May 23, 2019 10:32
-
-
Save kmelve/beee0a58a86aa8830b72d43de5e85582 to your computer and use it in GitHub Desktop.
Dated publishing in Gatsby and Sanity.io
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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