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

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.

Related

Getting an error when having heuristic fragment matching with Apollo & Nuxt.js

I am trying to connect the below graphql query with nuxtjs.
query getContent($slug: String!) {
contents (filters: { slug: { eq: $slug } }) {
data {
id
attributes {
title
content {
__typename
... on ComponentContentParagraph {
content
}
}
}
}
}
}
I am getting the following error and not getting the result from the query.
You are using the simple (heuristic) fragment matcher, but your queries contain union or interface types. Apollo Client will not be able to accurately map fragments. To make this error go away, use the `IntrospectionFragmentMatcher` as described in the docs: https://www.apollographql.com/docs/react/advanced/fragments.html#fragment-matcher
I have checked the questions and answers available here.
Apollo+GraphQL - Heuristic Fragment Manual Matching
I have followed the docs from apollo as well.
https://www.apollographql.com/docs/react/data/fragments/#fragment-matcher
I managed to generate possibleTypes as mentioned in the docs.
Here is my next config.
apollo: {
includeNodeModules: true,
clientConfigs: {
default: "~/graphql/default.js",
},
},
This is the default.js
import { InMemoryCache } from "apollo-cache-inmemory";
import possibleTypes from "./possibleTypes.json";
export default () => {
return {
httpEndpoint: process.env.BACKEND_URL || "http://localhost:1337/graphql",
cache: new InMemoryCache({ possibleTypes }),
};
};
I am using strapi for the backend and this query works fine when running from graphql interface.

Missing 'fixed' and 'fluid' fields on image asset with `gatsby-source-sanity`

I'm trying to source images from Sanity with gatsby-source-sanity and gatsby-image. In the past I've had no issue querying the fluid image asset like so:
export const query = graphql`
query {
allSanityPicture {
nodes {
image {
asset {
fluid(maxWidth: 900) {
...GatsbySanityImageFluid
}
}
}
}
}
}
`;
However, for some reason the fluid and fixed fields of asset aren't showing up in GraphQL:
There's definitely an image on the node, as the url field works.
I've installed and configured my Gatsby plugins as required:
plugins: [
{
resolve: `gatsby-source-sanity`,
options: {
projectId: `mhlt1wid`,
dataset: `production`,
token: process.env.SANITY_TOKEN,
}
},
`gatsby-plugin-sharp`,
`gatsby-transformer-sharp`,
],
and deployed the GraphQL API with sanity graphql deploy.
What am I missing here? Have tried from scratch twice now on two fresh projects and still having the same issue.
What version of Gatsby were you using when you wrote this and what version did you downgrade to?
The GraphQL query format for Gatsby 4 has changed along with the gatsby-image component being deprecated in favor of gatsby-plugin-image.
According to this Gatsby article on migration, the older fragment-based method you use
...
image {
asset {
fluid(maxWidth: 900) {
...GatsbySanityImageFluid
}
}
...
should be replaced in favor of the new syntax passing things like layout and format to the gatsbyImageData() resolver. The 'fluid' image type and 'maxWidth' have also been replaced with CONSTRAINED (in your case, or FULL_WIDTH if you want to just allow your tag to set the width of the image) and WIDTH which is understood as a maximum width for constrained type images. So in Gatsby 4 using gatsby-plugin-image your code should look something like:
...
image {
asset {
gatsbyImageData(layout: CONSTRAINED, width: 900)
}
}
...
Here is more information about the new component and API, and here is a useful discussion of the new CONSTRAINED layout being used with width at the request.

Using frontmatter in a markdownfile to query for images in a page query

I'm using GraphQL from within a Gatsby project. I have a set of markdown files for a blog-like section of the site. In the frontmatter of each markdown file, there's an image property.
What I'd like to do is use Gatsby's fine image api to load the image in the frontmatter. When viewing an individual post (the ones created via createPage api), this works just fine because I can provide the frontmatter.image in the context. Here's what that query looks like.
export const pageQuery = graphql`
query($slug: String!, $image: String) {
markdownRemark(frontmatter: { slug: { eq: $slug } }) {
html
frontmatter {
date(formatString: "MMMM DD, YYYY")
slug
title
image
}
}
coverImage: file(relativePath: { eq: $image }) {
childImageSharp {
fluid(maxWidth: 1440) {
...GatsbyImageSharpFluid
}
}
}
}
`
On my index page where I'm displaying all these posts though, I want to display a smaller version of this image. I can get the image from the front matter easy enough, but I'm not sure how to integrate that into the query.
export const pageQuery = graphql`
query {
allMarkdownRemark(sort: { order: DESC, fields: [frontmatter___date] }) {
edges {
node {
id
excerpt(pruneLength: 250)
frontmatter {
date(formatString: "MMMM DD, YYYY")
slug
title
image # <--- want to use this in a file query
}
}
}
}
}
`
As far as I understand, I can't use string interpolation in a static query in the component where the image is actually used, so I need to get it here in the page query. Is what I'm trying to do possible? Is there a better way to handle this?
This "link" between your frontmatter's image string and an actual image file node (processed with Sharp) is called a foreign-key relationship.
Creating foreign-key relationships in Gatsby
There are two ways of doing this:
Using mappings in gatsby-config.js
Using a GraphQL #link directive through Gatsby's schema customization (from v2.2)
I recommend the second option, since it's a more GraphQL way of doing things, and happens in gatsby-node.js where most node operations are taking place. However, if you're starting out with Gatsby and GraphQL, the first option might be easier to set up.
Implementing the #link directive in gatsby-node.js
In your case, using the #link GraphQL directive, you would probably end up with something like this in your gatsby-node.js:
exports.createSchemaCustomization = ({ actions }) => {
const { createTypes } = actions
const typeDefs = [
`type MarkdownRemark implements Node { frontmatter: Frontmatter }`,
`type Frontmatter {
# you may need to adapt this line depending on the node type and key
# that you want to create the relationship for
image: File #link(by: "relativePath")
}`
]
createTypes(typeDefs)
}
If you want to see an example in the wild, check out gatsby-node.js in robinmetral/eaudepoisson.com.
Query processed images via your frontmatter
Finally, you'll be able to query like this:
{
allMarkdownRemark {
edges {
node {
frontmatter {
date
slug
title
# image now points to the image file node
image {
childImageSharp {
fluid(maxWidth: 1024) {
...GatsbyImageSharpFluid
}
}
}
}
}
}
}
}

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
}`

ButterCMS: Unknown field on RootQueryType

Hello Im trying to query data into Gatsby from ButterCMS by following the documentation in gatsby-source-buttercms(https://www.gatsbyjs.org/packages/gatsby-source-buttercms/#gatsby-source-buttercms). But got the error "unknown field allButterJob on RootQueryType". I dont know what i did wrong. Someone please take a look at this for me. Here's my gatsby-config.js:
module.exports = {
siteMetadata: {
title: 'Gatsby Default Starter',
},
plugins: [
'gatsby-plugin-react-helmet',
{
resolve: 'gatsby-source-buttercms',
options: {
authToken: '2a926fdcab34e736332a54e24649cedbaf5d0e89',
contentFields: {
keys: [ // Comma delimited list of content field keys.
'job',
'news'
],
test: 0 // Optional. Set to 1 to enable test mode for viewing draft content.
}
}
}
],
}
Here's where i made the query:
import React from 'react'
import Link from 'gatsby-link'
import HeaderlineSection from '../components/headerlineSection'
import FeatureSection from '../components/featureSection'
import TeamSection from '../components/teamSection'
import NewsSection from '../components/newsSection'
import CareerSection from '../components/careerSection'
const IndexPage = ({data}) => (
<div>
<HeaderlineSection />
<FeatureSection />
<TeamSection />
<NewsSection />
<CareerSection />
{console.log(data)}
</div>
)
export default IndexPage
export const query = graphql`
query IndexPageQuery{
allButterJob{
edges{
node{
id
title
}
}
}
}
`
RootQueryType is the top level “item” in your GraphQL schema (Gatsby v1 sets this up). So the relevant part of the error here is “unknown field allButterJob”, which is pretty self explanatory: the field/type you're trying to query doesn't exist at the top level.
It's likely that it's there under a different name. Usually I hop into Graphiql (localhost:8000/___graphql if you're running gatsby develop under the standard port), where you will see something like this in the sidebar (click on the Docs link if it isn't showing):
From here you can click on “Query” to drill down into it. (Note that this screenshot is from a Gatshy v2 app, so instead of RootQueryType it's just listed as Query.) That'll pull up a list of the fields available on Query (or in your case, RootQueryType) that looks something like this:
In this example, allSitePage is a top-level field available to query like this:
query AnythingYouLikeHere {
allSitePage {
edges {
node {
path
}
}
}
}

Resources