Skip to content

Instantly share code, notes, and snippets.

@kandros
Created March 31, 2020 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kandros/0e25434638e06d37ba52a95f811810a8 to your computer and use it in GitHub Desktop.
Save kandros/0e25434638e06d37ba52a95f811810a8 to your computer and use it in GitHub Desktop.
gatsby blog next prev
const path = require(`path`)
const { createFilePath } = require(`gatsby-source-filesystem`)
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions
const blogPost = path.resolve(`./src/templates/blog-post.js`)
const postsPromise = graphql(
`
{
allMarkdownRemark(
filter: {
fields: { collection: { eq: "blog" } }
frontmatter: { draft: { ne: true } }
}
sort: { fields: [frontmatter___date], order: DESC }
limit: 1000
) {
edges {
node {
fields {
slug
}
frontmatter {
title
}
}
}
}
}
`
).then(result => {
if (result.errors) {
throw result.errors
}
// Create blog posts pages.
const posts = result.data.allMarkdownRemark.edges
posts.forEach((post, index) => {
const previous = index === posts.length - 1 ? null : posts[index + 1].node
const next = index === 0 ? null : posts[index - 1].node
createPage({
path: post.node.fields.slug,
component: blogPost,
context: {
slug: post.node.fields.slug,
previous,
next,
},
})
})
})
const noteComponent = path.resolve(`./src/templates/blog-post.js`)
const notesPromise = graphql(
`
{
allMarkdownRemark(
filter: { fields: { collection: { eq: "notes" } } }
sort: { fields: [frontmatter___date], order: DESC }
limit: 1000
) {
edges {
node {
fields {
slug
}
frontmatter {
title
}
}
}
}
}
`
).then(result => {
if (result.errors) {
throw result.errors
}
const notes = result.data.allMarkdownRemark.edges
notes.forEach((note, index) => {
const previous = index === notes.length - 1 ? null : notes[index + 1].node
const next = index === 0 ? null : notes[index - 1].node
createPage({
path: "notes" + note.node.fields.slug,
component: noteComponent,
context: {
slug: note.node.fields.slug,
previous,
next,
},
})
})
})
return Promise.all([notesPromise, postsPromise])
}
exports.onCreateNode = ({ node, actions, getNode }) => {
const { createNodeField } = actions
if (node.internal.type === `MarkdownRemark`) {
const value = createFilePath({ node, getNode })
const parent = getNode(node.parent)
createNodeField({
node,
name: "collection",
value: parent.sourceInstanceName,
})
createNodeField({
name: `slug`,
node,
value,
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment