如何在 GraphQL 中处理多种类型的数组(例如:不同的内容块)? [英] How do you handle an array of multiple types (ex: different content blocks) in GraphQL?

查看:30
本文介绍了如何在 GraphQL 中处理多种类型的数组(例如:不同的内容块)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let's say I have a page builder field that references many different types of content blocks.

  • 视频
  • 引用
  • 广告

等等...

据我所知,不鼓励在数组中使用多种类型.

From what I've read, having multiple types in an array is discouraged.

但是在这种情况下你还能做什么?

But what else are you supposed to do in a case like this?

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

Is there a way to handle this in GraphQL?

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

Is there a better way to structure the data?

推荐答案

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

You could define them as a union (or interface if all implementing types share common fields)

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
    }
  }
}

更多阅读 GraphQL 中的联合和接口

这篇关于如何在 GraphQL 中处理多种类型的数组(例如:不同的内容块)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆