I have a graphql query for Markdown files which requests the title, author and coverImg from the frontmatter of the Markdown.
Some Markdown files do not have a cover image, when there is no image, then it looks like the type of coverImg is String
I am using gatsby-image which uses sharp and I would like to descend into the children of the coverImg parameter, if the coverImg is an object and not a string
This is my query
query($path: String!) {
markdownRemark(fields: { slug: { eq: $path } }) {
frontmatter {
title
author
coverImg {
childImageSharp {
fluid(maxWidth: 600) {
src
srcSet
sizes
aspectRatio
}
}
}
}
}
}
If I try this I receive the error
There was an error in your GraphQL query:
Field "cover" must not have a selection since type "String" has no subfields.
This can happen if you e.g. accidentally added { } to the field "cover". If you didn't expect "cover" to be of type "String" make sure that your input source and/or plugin is correct.
It looks like there's graphql if statements but I don't know how to use these to conditionally branch to children. It would be great if I could just add something like
coverImg @skip(if: coverImg is String) {
AFAIK Gatsby doesn't infer the schema of your data on a per-file basis, so once it infer a field as String, that field will always be of type String.
You can use the schema customization hook to tell Gatsby that the field coverImg is a file (as suggested by @ksav in the comment):
exports.createSchemaCustomization = ({ actions }) => {
actions.createTypes(`
type MarkdownRemarkFrontmatter @infer {
coverImg: File
}
type MarkdownRemark implements Node @infer {
frontmatter: MarkdownRemarkFrontmatter
}
`)
}
Then you can check if coverImg exists.
if (!coverImg) {
// no image
} else if (coverImg.childImageSharp) {
// has image
} else {
// file is not an image
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With