GQL scheme to accept multiple data structure for same key

55 views Asked by At

I'm currently using GQL Modules in my app.

In the below data structure, content will have either object or array

var A = {
  content: {
    text: "Hello"
  }
}

var B = {
  content: {
    banner: [{
      text: "Hello"
    }]
  }
}

How do I make content to accept dynamic schema ?

Below is what I tired, but not working. Please help

type body {
 content: TextContent | [Banner]
}

type Banner {
  text: TextContent
}

type TextContent {
 text: String
}
1

There are 1 answers

0
Daniel Rearden On BEST ANSWER

GraphQL requires that a field always resolves to either a single value or a list -- it cannot resolve to either. A field can however, return different types altogether at runtime using an abstract type (either a union or an interface). So you can restructure your schema like this:

type Body {
  content: Content
}

union Content = TextContent | BannerContent

type TextContent {
  text: String
}

type BannerContent {
  banners: [Banner]
}

You would then query content using fragments:

query {
  someField {
    body {
      content: {
        ...on TextContent {
          text
        }
        ...on BannerContent {
          banners
        }

      }
    }
  }
}