Andrea Nicolai
Andrea Nicolai

Reputation: 440

How Gatsby handles unions of graphql types

I'm developing a react app typescript using Gatsbyjs.

These are some of the packages installed that might be useful to mention:

"gatsby": "^5.14.1"
"gatsby-transformer-json": "^5.14.0"
"gatsby-source-filesystem": "^5.14.0",

I want to populate some pages using data fetched from a JSON that looks like the following:

{
  "mydata": [
    {
      "contentType": "TextType",
      "size": "medium",
      "font": "Arial",
      "content": [
        "Some content"
      ]
    },
    {
      "contentType": "ImageType",
      "maxWidth": 500,
      "content": [
        "image1.png"
      ]
    },
    {
      "contentType": "TemplateType",
      "template": "custom",
      "innerContent": [
        {
          "contentType": "TextType",
          "size": "small",
          "content": [
            "Nested content"
          ]
        }
      ]
    }
  ]
}

Note that innerContent, which exists only in entries where contentType === "TemplateType" as children can have a list of objects like TextType and ImageType. Whereas for the others is a list of string.

My gatsby-node.ts file has the following declaration:

export const createSchemaCustomization: GatsbyNode["createSchemaCustomization"] = ({ actions }) => {
  const { createTypes } = actions

  createTypes(`
    
    union ContentInnerType = TextType | ImageType
    union ContentOuterType = TemplateType | TextType | ImageType

    type TextType {
      contentType: String!
      size: String!
      font: String
      content: [String]!
    }

    type ImageType {
      contentType: String!
      maxWidth: Float
      content: [String]!
    }

    type TemplateType {
      contentType: String!
      template: String
      innerContent: [ContentInnerType]!
    }

    # Disable inference for DataJson to prevent type conflicts
    type DataJson implements Node @dontInfer {
      mydata: [ContentOuterType]
    }
  `)
}

However, even though the following seems reasonable and is actually suggested by the graphQL server itself:

query MyQuery {
  allDataJson {
    nodes {
      mydata{
        ... on TemplateType {
          template
        }
        ... on TextType {
          font
        }
        ... on ImageType {
          maxWidth
        }
      }
    }
  }
}

It raises an error that it cannot find any "type":

"errors": [
    {
      "message": "Cannot read properties of undefined (reading 'type')",
      "locations": [
        {
          "line": 4,
          "column": 7
        }
      ],
      "path": [
        "allDataJson",
        "nodes",
        0,
        "mydata",
        0
      ]
....
"data": {
    "allDataJson": {
      "nodes": [
        {
          "mydata": [
            null,
            null,
            null
          ]
        }
      ]
    }
  }

The query is legit, but I am not able to get any data. How to solve it?

Upvotes: 0

Views: 13

Answers (0)

Related Questions