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

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

问题描述

我有一个 类型的用户.用户也可以是 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天全站免登陆