gpt4 book ai didi

graphql - 您如何处理多种类型的数组(例如 : different content blocks) in GraphQL?

转载 作者:行者123 更新时间:2023-12-03 20:16:47 24 4
gpt4 key购买 nike

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

  • 视频
  • 报价
  • 广告

  • ETC...

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

    但是在这样的情况下你还应该做什么呢?

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

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

    最佳答案

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

    联合模式示例:

    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

    接口(interface)架构示例:
    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

    关于graphql - 您如何处理多种类型的数组(例如 : different content blocks) in GraphQL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52088172/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com