GraphQL 输入类型可以从其他类型或接口继承吗? [英] Can a GraphQL input type inherit from another type or interface?

查看:20
本文介绍了GraphQL 输入类型可以从其他类型或接口继承吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以对 GraphQL 输入类型使用继承?

Is it possible to use inheritance with GraphQL input types?

类似的东西(当然,这不适用于输入类型):

Something like that (this, of course, doesn't work with input types):

interface UserInputInterface {
  firstName: String
  lastName: String
}

input UserInput implements UserInputInterface {
  password: String!
}

input UserChangesInput implements UserInputInterface {
  id: ID!
  password: String
}

推荐答案

否,规范不允许输入类型实现接口.并且 GraphQL 类型系统通常不定义任何形式的继承(extends 关键字将字段添加到现有类型,而不是用于继承).规范被有意限制为保持简单.这意味着您不得不在输入类型之间重复字段.

No, the spec does not allow input types to implement interfaces. And GraphQL type system in general does not define any form of inheritance (the extends keyword adds fields to an existing type, and isn't for inheritance). The spec is intentionally constrained to stay simple. This means that you're stuck repeating fields across input types.

也就是说,根据您构建架构的方式,您可以构建某种类型转换器,基于某些元数据以编程方式附加公共字段,例如一个指令.

That said, depending on the way you construct your schema, you could build some kind of type transformer that appends the common fields programmatically based on some meta-data, e.g. a directive.

更好的是,您或许可以通过组合来解决您的问题(始终保持 组合继承).例如

Better yet, you might be able to solve your problem via composition (always keep composition over inheritance in mind). E.g.

input Name {
  firstName: String
  lastName: String
}

input UserInput {
  name: Name
  password: String!
}

input UserChangesInput {
  name: Name
  id: ID!
  password: String
}

客户端现在必须发送一个更深层次的对象,但这听起来不像是避免大重复块的代价.这实际上可能对客户端也有好处,因为他们现在可以拥有构建名称的通用逻辑,而不管使用它们的查询/变异如何.

The client now has to send an object a level deeper, but that doesn't sound like much of a price for avoiding big repeating chunks. It might actually be good for the client as well, as they can now have common logic for building names, regardless of the query/mutation using them.

在这个例子中,只有 2 个简单的字段,这种方法有点矫枉过正,但总的来说 - 我会说这是要走的路.

In this example, where it's only 2 simple fields, this approach is an overkill, but in general - I'd say it's the way to go.

这篇关于GraphQL 输入类型可以从其他类型或接口继承吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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