Created
January 19, 2020 19:18
-
-
Save fusepilot/316bf113a13d775cfbff5a86f639195f to your computer and use it in GitHub Desktop.
Gatsby Schema @link to MarkdownRemark slug from SitePage
This file contains hidden or 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 path = require("path"); | |
const { createFilePath } = require(`gatsby-source-filesystem`); | |
exports.createPages = async ({ graphql, actions }) => { | |
const result = await graphql( | |
` | |
{ | |
allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) { | |
edges { | |
node { | |
fields { | |
slug | |
} | |
} | |
} | |
} | |
} | |
` | |
); | |
if (result.errors) { | |
throw result.errors; | |
} | |
result.data.allMarkdownRemark.edges.forEach(({ node }) => { | |
const component = path.resolve(`src/templates/post.js`); | |
actions.createPage({ | |
path: node.fields.slug, | |
component, | |
context: { | |
slug: node.fields.slug | |
} | |
}); | |
}); | |
}; | |
exports.onCreateNode = ({ node, getNode, actions }) => { | |
if (node.internal.type === `MarkdownRemark`) { | |
const slug = createFilePath({ node, getNode, basePath: `content` }); | |
actions.createNodeField({ | |
node, | |
name: `slug`, | |
value: slug | |
}); | |
} | |
}; | |
exports.createSchemaCustomization = ({ actions }) => { | |
const typeDefs = ` | |
type SitePageFields { | |
markdownRemark: MarkdownRemark @link(to: "fields.slug", from: "context.slug") | |
} | |
type SitePage implements Node { | |
fields: SitePageFields | |
} | |
`; | |
actions.createTypes(typeDefs); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment