【问题标题】:How do you handle an array of multiple types (ex: different content blocks) in GraphQL?你如何在 GraphQL 中处理多个类型的数组(例如:不同的内容块)?
【发布时间】:2019-02-04 21:01:25
【问题描述】:

假设我有一个页面构建器字段,它引用了许多不同类型的内容块。

  • 视频
  • 报价
  • 广告

等等……

根据我的阅读,不鼓励在数组中包含多种类型。

但是在这种情况下,你还应该怎么做呢?

有没有办法在 GraphQL 中处理这个问题?

有没有更好的方法来构建数据?

【问题讨论】:

    标签: graphql contentful


    【解决方案1】:

    我相信,您可以实现接口列表或联合列表(基于数据的性质以及是否存在重复文件)。在该接口/联合中,您将实现所有这些类型(视频、报价、广告)。但是它适用于数据获取,但接口或联合不能用作输入类型。如果您想将其实现为输入类型,则需要使用例如 JSON 自定义标量 https://github.com/taion/graphql-type-json

    编辑:我不认为在界面内的列表中有多种类型是不好的做法。您可以查看节点查询或搜索 Github api https://developer.github.com/v4/query/

    【讨论】:

      【解决方案2】:

      您可以将它们定义为联合(如果所有实现类型共享公共字段,则可以定义为接口)

      联合模式示例:

      type Query {
        blocks: [ ContentBlock! ]!
      }
      
      type Video {
        url: String!
      }
      
      type Quote {
        body: String!
        author: String
      }
      
      type Advertisement {
        src: String!
        backgroundColor: String
      }
      
      
      union ContentBlock = Video | Quote | Advertisement
      

      接口架构示例:

      type Query {
        blocks: [ ContentBlock! ]!
      }
      
      type Video implements ContentBlock {
        id: ID!
        url: String!
      }
      
      type Quote implements ContentBlock {
        id: ID!
        body: String!
        author: String
      }
      
      type Advertisement implements ContentBlock {
        id: ID!
        src: String!
        backgroundColor: String
      }
      
      
      interface ContentBlock {
        id: ID!
      }
      

      示例解析器:

      {
        ContentBlock: {
          __resolveType (source) {
            if (source.url) return 'Video'
            if (source.src) return 'Advertisment'
            if (source.author || source.body) return 'Quote'
          }
        }
      }
      

      查询示例:

      {
        blocks {
          ...on Video {
            url
          }
          ...on Quote {
            body
            author
          }
          ...on Advertisement {
            src
            backgroundColor
          }
        }
      }
      

      More reading on Unions and Interfaces in GraphQL

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-27
        • 2012-12-09
        • 1970-01-01
        • 2018-09-29
        • 2021-04-27
        • 2021-05-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多