【问题标题】:GQL scheme to accept multiple data structure for same keyGQL 方案接受相同键的多个数据结构
【发布时间】:2020-05-18 23:13:21
【问题描述】:

我目前在我的应用中使用GQL Modules

在下面的数据结构中,content 将具有objectarray

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

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

如何让content 接受动态架构?

下面是我累了,但没有工作。请帮忙

type body {
 content: TextContent | [Banner]
}

type Banner {
  text: TextContent
}

type TextContent {
 text: String
}

【问题讨论】:

    标签: graphql apollo apollo-client gql gqlquery


    【解决方案1】:

    GraphQL 要求字段始终解析为单个值或列表——它不能解析为任何一个。但是,字段可以在运行时使用抽象类型(联合或接口)完全返回不同的类型。所以你可以像这样重组你的架构:

    type Body {
      content: Content
    }
    
    union Content = TextContent | BannerContent
    
    type TextContent {
      text: String
    }
    
    type BannerContent {
      banners: [Banner]
    }
    

    然后您将使用片段查询content

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

    【讨论】:

      猜你喜欢
      • 2017-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-11
      • 2015-08-17
      相关资源
      最近更新 更多