Reputation: 43
Hi. I have a Gatsby website and I am making use of the gatsby-transformer-remark
plugin to get a load of blog markdown files from a blog directory into GraphQL to display on my site. I have looked at the docs and example code to see how to create a slug for each page so that in the gatsby-node.js
file I can create pages with the slug dynamically.
When I try to access the fields { slug }
property in GraphiQL I get the following error:
message": "Cannot query field \"fields\" on type \"MarkdownRemark\"."
I have checked my setup a couple of times and I think it all seems good so I'm not 100% sure what I have missed to not have these fields. I can access other informations such as the raw content of the markdown files and the frontmatter data, just not the fields.
In My gatsby-config.js
plugins I have the following setup for the source filesystem and the remark plugin
{
resolve: `gatsby-source-filesystem`,
options: {
name: `blog`,
path: `${__dirname}/blog`,
},
},
{
resolve: `gatsby-transformer-remark`,
options: {
plugins: [
{
resolve: `gatsby-remark-images`,
options: {
maxWidth: 960,
},
},
`gatsby-remark-prismjs`,
`gatsby-remark-copy-linked-files`,
],
},
},
Once I am in GraphiQL I run the following query to replicate the error
query {
allMarkdownRemark(
sort: { fields: [frontmatter___date], order: DESC }
limit: 1000
) {
edges {
node {
fields {
slug
}
frontmatter {
title
}
}
}
}
}
Upvotes: 4
Views: 1281
Reputation: 29320
As you can see, slug
field is not a child of frontmatter
(as natively should if you work with raw markdowns). To make the slug
available as children of field
, you need to add the following snippet in your gatsby-node.js
:
const { createFilePath } = require(`gatsby-source-filesystem`)
exports.onCreateNode = ({ node, getNode, actions }) => {
const { createNodeField } = actions
if (node.internal.type === `MarkdownRemark`) {
const slug = createFilePath({ node, getNode, basePath: `pages` })
createNodeField({
node,
name: `slug`,
value: slug,
})
}
}
Adding this configuration with createNodeField
API you are allowing Gatsby and the inferred GraphQL schema to create additional fields on nodes created by other plugins by telling Gatsby that if the node type is a markdown, create a slug
field based on the slug
value of the frontmatter
.
You can check for further information in Gatsby's docs.
Upvotes: 5