Allow optional GraphQL data in Gatsby

Asked
Active3 hr before
Viewed126 times

9 Answers

optionalallowgraphql
90%

String! means that the field is non-nullable, meaning that the GraphQL service promises to always give you a value when you query this field. In the type language, we'll represent those with an exclamation mark.,The exclamation point ! in GraphQL means non-nullable, so [String!]! means that there is a non-null array of non-null strings.,If you want a field to be optional, just leave it as it is without exclamation points !. For example [String] means that the array can be null, or any of the string values inside it can be null.

As per the Gatsby docs, I think what you're looking for is this:

const typeDefs = `
    type markdownRemark implements Node {
        // Use custom frontmatter type
        frontmatter: Frontmatter
    }
    // Define custom frontmatter type
    type FrontMatter {
      // Nullable array of Feature elements
      features: [Feature]
    }
    // Feature has nullable fields title and description
    type Feature {
        title: String
        description: String
    }
`;
88%

Defining child relations,Including the __typeName introspection field allows to check the node type when iterating over the query results in your component:,Creating custom extensions

Pretag
 Pretag team - issue, fix, solve, resolve
72%

Hello, I'm using Gatsby with the Wordpress source plugin. So far so good. But the thing is I am querying fields that might or might not be there, in this case, the featured image of a post. Here is my query:,Was getting the same issue while using gatsby-source-wordpress to query Woocommerce coupons, in which all of the fields are optional. The quoted answer along with the answer at following link provided the solution. Thanks! https://stackoverflow.com/questions/60289062/allow-optional-graphql-data-in-gatsby,@KyleAMathews Just thought I'd let everyone know aswell that we are experiencing the same issue here in London, UK - using gatsby-source-wordpress

{
   allWordpressPost(sort: {
      fields: [date]
   }) {
      edges {
         node {
            title
            excerpt
            slug
            featured_media
            better_featured_image {
               wordpress_id
               alt_text
               caption
               description
               media_type
               post
               source_url
            }
         }
      }
   }
}
load more v
65%

Pretag
 Pretag team - issue, fix, solve, resolve
75%

In order to source this data into our GraphQL data layer we will need to use two Gatsby plugins: gatsby-source-filesystem and gatsby-transform-json. Let’s add these plugins to our Gatsby project:,In order to query for our author’s posts and also get our post by author we need to create a relationship in Gatsby so our GraphQL data layer can include the related content in our queries.,Gatsby uses GraphQL to enable page and StaticQuery components to declare what data they and their sub-components need. Then, Gatsby makes that data available in the browser when needed by your components.

Pretag
 Pretag team - issue, fix, solve, resolve
40%

It's often useful to ask a GraphQL schema for information about what queries it supports. GraphQL allows us to do so using the introspection system!,It's useful for an object to know what fields are available, so let's ask the introspection system about Droid:,So we can access the documentation about the type system using introspection, and create documentation browsers, or rich IDE experiences.

Pretag
 Pretag team - issue, fix, solve, resolve
22%

By default, gatsby-source-graphql will only refetch the data once the server is restarted. It's also possible to configure the plugin to periodically refetch the data. The option is called refetchInterval and specifies the timeout in seconds.,The return value is expected to be the final schema used for stitching.,Below an example configuration that uses the default implementation (equivalent to not using the transformSchema option at all):

// In your gatsby-config.js
module.exports = {
   plugins: [
      // Simple config, passing URL
      {
         resolve: "gatsby-source-graphql",
         options: {
            // Arbitrary name for the remote schema Query type
            typeName: "SWAPI",
            // Field under which the remote schema will be accessible. You'll use this in your Gatsby query
            fieldName: "swapi",
            // Url to query from
            url: "https://swapi-graphql.netlify.app/.netlify/functions/index",
         },
      },

      // Advanced config, passing parameters to apollo-link
      {
         resolve: "gatsby-source-graphql",
         options: {
            typeName: "GitHub",
            fieldName: "github",
            url: "https://api.github.com/graphql",
            // HTTP headers
            headers: {
               // Learn about environment variables: https://gatsby.dev/env-vars
               Authorization: `Bearer ${process.env.GITHUB_TOKEN}`,
            },
            // HTTP headers alternatively accepts a function (allows async)
            headers: async () => {
               return {
                  Authorization: await getAuthorizationToken(),
               }
            },
            // Additional options to pass to node-fetch
            fetchOptions: {},
         },
      },

      // Advanced config, using a custom fetch function
      {
         resolve: "gatsby-source-graphql",
         options: {
            typeName: "GitHub",
            fieldName: "github",
            url: "https://api.github.com/graphql",
            // A `fetch`-compatible API to use when making requests.
            fetch: (uri, options = {}) =>
               fetch(uri, {
                  ...options,
                  headers: sign(options.headers)
               }),
         },
      },

      // Complex situations: creating arbitrary Apollo Link
      {
         resolve: "gatsby-source-graphql",
         options: {
            typeName: "GitHub",
            fieldName: "github",
            // Create Apollo Link manually. Can return a Promise.
            createLink: pluginOptions => {
               return createHttpLink({
                  uri: "https://api.github.com/graphql",
                  headers: {
                     Authorization: `Bearer ${process.env.GITHUB_TOKEN}`,
                  },
                  fetch,
               })
            },
         },
      },
   ],
}
load more v
60%

Next let's add a GraphQL query to get our books data into this page. The updated code will look like this:,We'll be able to use anything passed in this context property in our GraphQL queries in our blog component.,We can add on to this query to return the path of all the pages. This query will look like the following:

1 gatsby new booksplus
load more v
48%

Replace the value of the uri option with your GraphQL server's subscription-specific WebSocket endpoint. If you're using Apollo Server, see Setting a subscription endpoint.,When to use subscriptions,You define a subscription on both the server side and the client side, just like you do for queries and mutations.

type Subscription {
   commentAdded(postID: ID!): Comment
}
load more v

Other "optional-allow" queries related to "Allow optional GraphQL data in Gatsby"