Skip to content

Instantly share code, notes, and snippets.

@fusepilot
Created January 19, 2020 19:18
Show Gist options
  • Save fusepilot/316bf113a13d775cfbff5a86f639195f to your computer and use it in GitHub Desktop.
Save fusepilot/316bf113a13d775cfbff5a86f639195f to your computer and use it in GitHub Desktop.
Gatsby Schema @link to MarkdownRemark slug from SitePage
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