Gatsby - Cannot query field on type Error when field in CMS is empty - graphql

I found out that this is known problem with Strapi + Gatsby setup, but I found some articles about how to get rid of that error like the following ones:
https://www.virtualbadge.io/blog-articles/nullable-relational-fields-strapi-gatsbyjs-graphql
https://medium.com/swlh/gatsby-graphql-and-the-missing-but-necessary-explanation-about-type-definitions-87a5ef83e759
And indeed it helped with the bug itself, but caused another. At the moment when I fill the field inside the CMS graphql cannot see it and interprets it as null.
Without gatsby-node.ts:
And With gatsby-node.ts:
import type { GatsbyNode } from 'gatsby'
export const sourceNodes: GatsbyNode['sourceNodes'] = async ({ actions }) => {
const { createTypes } = actions
const typeDefs = `
type STRAPI__COMPONENT_BASE_HERO implements Node {
backgroundVideo: STRAPI__MEDIA
}
`
createTypes(typeDefs)
}

Related

How do I use sharp image with Strapi 4 and Gatsby 4

I'm want to use images from my Strapi V4 local backend to my Gatsby 4 using sharp image processing.
I was able to with Strapi 3 + Gatsby 3, but have recently upgraded to Strapi 4 and Gatsby 4 to avoid future deprecation.
This is my gatsby-config.js:
plugins: [
"gatsby-plugin-sass",
"gatsby-plugin-image",
"gatsby-plugin-sharp",
"gatsby-transformer-sharp",
{
resolve: "gatsby-source-graphql",
options: {
// Arbitrary name for the remote schema Query type
typeName: "STRAPI",
// Field under which the remote schema will be accessible. You'll use this in your Gatsby query
fieldName: "strapi",
// Url to query from
url: "http://localhost:1337/graphql",
},
}
]
This is a file (page within my gatsby site) i've been testing on, it doesn't work.
import React from "react";
import { graphql } from "gatsby"
import { GatsbyImage, getImage } from "gatsby-plugin-image"
const Test = ({ data }) => {
const image = getImage(strapi.food.data.attribute.thumbnail.data.attribute)
return (
<div>
<GatsbyImage image={image} alt={"Come on!"} />
</div>
)
}
export const pageQuery = graphql`
query FoodQuery {
strapi {
food(id: "67") {
data {
attributes {
name
thumbnail {
data {
attributes {
childImageSharp {
gatsbyImageData(width: 200)
}
}
}
}
}
}
}
}
}
`
export default Test;
The error I keep getting is.
25:17 error Cannot query field "childImageSharp" on type "STRAPI_UploadFile" graphql/template-strings
I've tried many things. I've checked to see if I can at least pull text and number fields, I can, all of them even attributes in the thumbnails object like createdAt.
I've checked to see if permissions are correct, and they seem fine - find, fineOne are both checked for the content-type and upload.
I've tried to query the uploadFile. And tried to pull food items one at a time and as a array/list of foods.
I've tried changing where I've placed childImageSharp as well as moving brackets around.
Edit: This is my GraphiQl sandbox with everything I can gather.

Optional queries in Gatsby / GraphQL

I have a Gatsby site with a contentful source, the initial page build GraphQL looks like this:
{
allContentfulProduct {
edges {
node {
slug
contentfulid
}
}
}
}
this works fine when using the preview API, but when using the production one it fails unless I have at least 1 Product entry published:
There was an error in your GraphQL query:
Cannot query field "allContentfulProduct" on type "Query". Did you mean ... [suggested entry names] ?
I'm pretty sure that when I publish a Product things will work as expected, but is there any way to make this query optional. The query should return zero results, and thus no Product pages will be created (expected outcome if no Product entries are published)
Try to add into your gatsby-node.js file and play around that.
exports.createSchemaCustomization = ({ actions }) => {
const { createTypes } = actions
const typeDefs = `
type allContentfulProduct implements Node{
slug: String,
contentfulid: String
}`

Use absolute path for featured image in markdown post with Gatsby

I've followed Gatsby tutorial for Working With Images in Markdown Posts and Pages which is working well but what I want to achieve is to fetch image from a static location instead of using a relative path for the image.
Would like to reference image like this (in frontmatter)
featuredImage: img/IMG_20190621_112048_2.jpg
Where IMG_20190621_112048_2.jpg is in /src/data/img instead of same directory as markdown file under /src/posts
I've tried to setup gatsby-source-filesystem like this :
{
resolve: `gatsby-source-filesystem`,
options: {
name: `posts`,
path: `${__dirname}/src/posts`,
},
},
{
resolve: `gatsby-source-filesystem`,
options: {
name: `data`,
path: `${__dirname}/src/data/`,
},
},
but graphQL query in post template fails :
export const query = graphql`
query($slug: String!) {
markdownRemark(fields: { slug: { eq: $slug } }) {
html
frontmatter {
title
featuredImage {
childImageSharp {
fluid(maxWidth: 800) {
...GatsbyImageSharpFluid
}
}
}
}
}
}
GraphQL Error Field "featuredImage" must not have a selection since
type "String" has no subfields.
Any idea how I could fetch image from a location distinct to the post markdown directory ?
Achieving this in Gatsby used to be pretty troublesome, but thanks to the new createSchemaCustomization Node API docs (since Gatsby 2.5) it's relatively easy.
Here's a demo where I replicate your repo structure: github
Here's where the relevant code lives: github
Here's the code to make it work:
// gatsby-node.js
const path = require('path')
exports.createSchemaCustomization = ({ actions }) => {
const { createFieldExtension, createTypes } = actions
createFieldExtension({
name: 'fileByDataPath',
extend: () => ({
resolve: function (src, args, context, info) {
const partialPath = src.featureImage
if (!partialPath) {
return null
}
const filePath = path.join(__dirname, 'src/data', partialPath)
const fileNode = context.nodeModel.runQuery({
firstOnly: true,
type: 'File',
query: {
filter: {
absolutePath: {
eq: filePath
}
}
}
})
if (!fileNode) {
return null
}
return fileNode
}
})
})
const typeDefs = `
type Frontmatter #infer {
featureImage: File #fileByDataPath
}
type MarkdownRemark implements Node #infer {
frontmatter: Frontmatter
}
`
createTypes(typeDefs)
}
How it works:
There are 2 parts to this:
Extend markdownRemark.frontmatter.featureImage so graphql resolves to a File node instead of a string via createTypes
Create a new field extension #fileByDataPath via createFieldExtension
createTypes
Right now Gatsby's inferring frontmatter.featureImage as a string. We'll ask Gatsby to read featureImage as a string instead, by modifying its parent type:
type Frontmatter {
featureImage: File
}
This is not enough however, we'll also need to pass this Frontmatter type to its parent as well:
type Frontmatter {
featureImage: File
}
type MarkdownRemark implements Node {
frontmatter: Frontmatter
}
We'll also add the #infer tag, which lets Gatsby know that it can infer other fields of these types, i.e frontmatter.title, markdownRemark.html, etc.
Then pass these custom type to createTypes:
exports.createSchemaCustomization = ({ actions }) => {
const { createTypes } = actions
const typeDefs = `
type Frontmatter #infer {
featureImage: File
}
type MarkdownRemark implements Node #infer {
frontmatter: Frontmatter
}
`
createTypes(typeDefs)
}
Now, we can fire up localhost:8000/___graphql and try to query the image
query Post {
markdownRemark {
frontmatter {
featureImage {
id
}
}
}
}
and we get...
Error: Cannot return null for non-nullable field File.id.
That is because while Gatsby now understands featureImage should be a File node, it has no idea where to get that file.
At this point, we can either use createResolvers to manually resolve the field to a File node, or createFileExtension to do the same thing. I choose createFileExtension because it allows more code reuse (you can extend any fields), while createResolvers, in this case, is more useful for a specific field. Seeing that all you want is to resolve a file from the src/data directory, I'll call this extension fieldByDataPath.
createFileExtension
Let's just look at the resolve attribute. It is a function that takes in the following:
source: The data of the parent field (in this case, frontmatter)
args: The arguments passed to featureImage in a query. We won't need this
context: contains nodeModel, which we'll use to get nodes from Gatsby node store
info: metadata about this field + the whole schema
We will find the original path (img/photo.jpg) from src.featureImage, then glue it to src/data to get a complete absolute path. Next, we query the nodeModel to find a File node with the matching absolute path. Since you have already pointed gatsby-source-filesystem to src/data, the image (photo.jpg) will be in Gatsby node store.
In case we can't find a path or a matching node, return null.
resolve: async function (src, args, context) {
// look up original string, i.e img/photo.jpg
const partialPath = src.featureImage
if (!partialPath) {
return null
}
// get the absolute path of the image file in the filesystem
const filePath = path.join(__dirname, 'src/data', partialPath)
// look for a node with matching path
const fileNode = await context.nodeModel.runQuery({
firstOnly: true,
type: 'File',
query: {
filter: {
absolutePath: {
eq: filePath
}
}
}
})
// no node? return
if (!fileNode) {
return null
}
// else return the node
return fileNode
}
We've done 99% of the work. The last thing to do is to move this to pass this resolve function to createFieldExtension; as well as add the new extension to createTypes
createFieldExtension({
name: 'fileByDataPath' // we'll use it in createTypes as `#fileByDataPath`
extend: () => ({
resolve, // the resolve function above
})
})
const typeDef = `
type Frontmatter #infer {
featureImage: File #fileByDataPath // <---
}
...
`
With that, you can now use relative path from src/data/ in frontmatter.
Extra
The way fileByDataPath implemented, it'll only work with fields named featureImage. That's not too useful, so we should modify it so that it'll work on any field that, say, whose name ended in _data; or at the very least accept a list of field names to work on.
Edit had a bit of time on my hand, so I wrote a plugin that does this & also wrote a blog on it.
Edit 2 Gatsby has since made runQuery asynchronous (Jul 2020), updated the answer to reflect this.
In addition to Derek Answer which allow assets of any type to be use anywhere (sound, video, gpx, ...), if looking for a solution only for images, one can use :
https://www.gatsbyjs.org/packages/gatsby-remark-relative-images/
The reason in your server schema you may have declared the featuredImage variable as string and in your client graphql query you are trying to call subobjects of the featuredImage variable and that subobjects is not existing.
You may have to check the graphql schema definition and align the query with the schema definition
you current schema might be like this
featuredImage: String
and you need to change it by declaring the proper types based on the requirements in the server side.
For more information about graphql types. please refer this url - https://graphql.org/learn/schema/#object-types-and-fields
Thanks
Rigin Oommen

GatsbyJs - How to handle empty graphql node from Contentful plugin

I am building a site in Gatsbyjs that pulls information in via the gatsby-source-contentful plugin, but I'm struggling with the graphql side of things.
If I have a Content model in Contentful that contains a field to override the default description for example - then if none of the content uses that yet graphql throws an error if I try to include it in my query.
Is there anyway to short circuit the graphql queries?
Examples
{
allContentfulPage {
edges {
node {
title
description {
description
}
}
}
}
}
This will break if there is no Page model that exists with a description, but as soon as one page gets a description it works.
Gatsby pulls data from Contentful and then it builds an internal "model" of what the data from Contenful looks like. The Contentful API is REST but internally Gatsby uses GraphQL.
If a field does not have a value on Contentful then it will not be a part of the generated GraphQL query in Gatsby. The solution is to push a single value in one of your records.
The other solution would be to create and define the ContentfulPage type in your gatsby-node.js file. here is the link to gatsby documentation if you need to read more .
To create types you could add this to your gatsby-node.js file:
const createSchemaCustomization = ({ actions }) => {
const types = [
`
type ContentfulPage implements Node {
description : ContentfullDescription
}
type ContentfullDescription implements Node {
description : String
}
`,
];
actions.createTypes(types);
};
const gatsbyNode = {
createSchemaCustomization,
};
export default gatsbyNode;
this is only the case if the description is a string, if it is some other type such as rich text you should add its type the createTypes api. then it would be:
const createSchemaCustomization = ({ actions }) => {
const types = [
`
type ContentfulPage implements Node {
description : ContentfullDescription
}
type ContentfullDescription implements Node {
description : ContentfulRichText
}
type ContentfulRichText {
raw: String
references: [Node] #link(from: "references___NODE")
}
`,
];
actions.createTypes(types);
};
const gatsbyNode = {
createSchemaCustomization,
};
export default gatsbyNode;
Please take note that I am just guessing the type of description it might be some other types that you need to create yourself.

Emit deprecation warnings with Apollo client

Background
We are working on a fairly large Apollo project. A very simplified version of our api looks like this:
type Operation {
foo: String
activity: Activity
}
type Activity {
bar: String
# Lots of fields here ...
}
We've realised splitting Operation and Activity does no benefit and adds complexity. We'd like to merge them. But there's a lot of queries that assume this structure in the code base. In order to make the transition gradual we add #deprecated directives:
type Operation {
foo: String
bar: String
activity: Activity #deprecated
}
type Activity {
bar: String #deprecated(reason: "Use Operation.bar instead")
# Lots of fields here ...
}
Actual question
Is there some way to highlight those deprecations going forward? Preferably by printing a warning in the browser console when (in the test environment) running a query that uses a deprecated field?
So coming back to GraphQL two years later I just found out that schema directives can be customized (nowadays?). So here's a solution:
import { SchemaDirectiveVisitor } from "graphql-tools"
import { defaultFieldResolver } from "graphql"
import { ApolloServer } from "apollo-server"
class DeprecatedDirective extends SchemaDirectiveVisitor {
public visitFieldDefinition(field ) {
field.isDeprecated = true
field.deprecationReason = this.args.reason
const { resolve = defaultFieldResolver, } = field
field.resolve = async function (...args) {
const [_,__,___,info,] = args
const { operation, } = info
const queryName = operation.name.value
// eslint-disable-next-line no-console
console.warn(
`Deprecation Warning:
Query [${queryName}] used field [${field.name}]
Deprecation reason: [${field.deprecationReason}]`)
return resolve.apply(this, args)
}
}
public visitEnumValue(value) {
value.isDeprecated = true
value.deprecationReason = this.args.reason
}
}
new ApolloServer({
typeDefs,
resolvers,
schemaDirectives: {
deprecated: DeprecatedDirective,
},
}).listen().then(({ url, }) => {
console.log(`🚀 Server ready at ${url}`)
})
This works on the server instead of the client. It should print all the info needed to track down the faulty query on the client though. And having it in the server logs seem preferable from a maintenance perspective.

Resources