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

查看:39
本文介绍了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天全站免登陆