如何在GraphQL中继承或扩展typeDefs [英] How to Inherit or Extend typeDefs in GraphQL

查看:737
本文介绍了如何在GraphQL中继承或扩展typeDefs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个type User.用户也可以是type TeamMember. UserTeamMember之间的唯一区别是添加的字段teamRole: String.因此,我很乐意做下面的事情,以避免不必要地重复定义所有用户字段…

I have a type User. Users can also be a type TeamMember. The only difference between a User and TeamMember is an added field teamRole: String. So, I’d love to do something like the following to avoid having to redundantly define all the user's fields…

  type User {
    id: ID!,
    name: String,
    (many other field defs)
  }

  type TeamMember extends User  {
    teamRole: String,
  }

有人知道这种语法吗?我以为extend是答案,但似乎更像是javascript的prototype

Anyone aware of a syntax for this? I thought extend would be the answer, but it seems more like javascript’s prototype

推荐答案

如果您有基本模式并希望基于该模式构建两个或多个可用模式,则extend关键字非常有用.例如,您可以使用所有模式共享的查询定义根Query类型,然后在每个单独的模式中扩展它以添加特定于该模式的查询.它也可以用于模块化架构.但是,这只是向现有类型添加功能的一种机制-不能用于创建新类型.

The extend keyword is great if you have a base schema and want to build two or more usable schemas based on it. You can, for example, define a root Query type with queries shared by all schemas, and then extend it within each individual schema to add queries specific to that schema. It can also be used to modularize a schema. However, it's only a mechanism to add functionality to existing types -- it can't be used to create new types.

GraphQL本质上不支持继承.没有语法可以帮助您避免多种类型的字段重复.

GraphQL does not inherently support inheritance. There is no syntax that would help you avoid duplication of fields across multiple types.

您可以利用字符串插值来避免一遍又一遍地输入相同的字段:

You can utilize string interpolation to avoid typing out the same fields again and again:

const sharedFields = `
  foo: String
  bar: String
`
const typeDefs = `
  type A {
    ${sharedFields}
  }

  type B {
    ${sharedFields}
  }
`

除非如此,您还可以利用类似 graphql-s2s 的库您可以利用继承和泛型类型.尽管以这种方式生成的模式仍然必须编译为有效的SDL,但充其量,像graphql-s2s这样的库仅提供一些语法糖和更好的DX.

Barring that, you can also utilize a library like graphql-s2s which allows you to utilize inheritance and generic types. Schemas generated this way still have to be compiled to valid SDL though -- at best, libraries like graphql-s2s just offer some syntactic sugar and a better DX.

最后,您可以重组您的类型,以完全避免字段重复,这是以更结构化的响应为代价的.例如,不要这样做:

Lastly, you can restructure your types to avoid the field duplication altogether at the cost of a more structured response. For example, instead of doing this:

type A {
  a: Int
  foo: String
  bar: String
}

type B {
  b: Int
  foo: String
  bar: String
}

您可以执行以下操作:

type X {
  foo: String
  bar: String
  aOrB: AOrB
}

union AOrB = A | B

type A {
  a: Int
}

type B {
  b: Int
}

这篇关于如何在GraphQL中继承或扩展typeDefs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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