您可以将 graphql 类型设为输入和输出类型吗? [英] Can you make a graphql type both an input and output type?

查看:19
本文介绍了您可以将 graphql 类型设为输入和输出类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一些对象类型用作输入和输出 - 例如货币类型或预订类型.

I have some object types that I'd like to use as both input and output - for instance a currency type or a reservation type.

我如何定义我的架构以具有同时支持输入和输出的类型 - 如果不需要,我不想复制代码.我也不想创建重复的输入类型,例如货币和状态枚举.

How do I define my schema to have a type that supports both input and output - I don't want to duplicate code if I don't have to. I'd also prefer not to create duplicate input types of things like currency and status enums.

export const ReservationInputType = new InputObjectType({
  name: 'Reservation',
  fields: {
    hotelId: { type: IntType },
    rooms: { type: new List(RoomType) },
    totalCost: { type: new NonNull(CurrencyType) },
    status: { type: new NonNull(ReservationStatusType) },
  },
});

export const ReservationType = new ObjectType({
  name: 'Reservation',
  fields: {
    hotelId: { type: IntType },
    rooms: { type: new List(RoomType) },
    totalCost: { type: new NonNull(CurrencyType) },
    status: { type: new NonNull(ReservationStatusType) },
  },
});

推荐答案

在 GraphQL 规范中,对象和输入对象是不同的东西.引用 输入对象的规范:

In the GraphQL spec, objects and input objects are distinct things. Quoting the spec for input objects:

字段可以定义客户端通过查询传递的参数,以配置它们的行为.这些输入可以是字符串或枚举,但有时需要比这更复杂.

Fields can define arguments that the client passes up with the query, to configure their behavior. These inputs can be Strings or Enums, but they sometimes need to be more complex than this.

对象类型...不适合在此处重用,因为对象可以包含表示循环引用或对接口和联合的引用的字段,这两者都不适合用作输入参数.因此,输入对象在系统中具有单独的类型.

The Object type... is inappropriate for re‐use here, because Objects can contain fields that express circular references or references to interfaces and unions, neither of which is appropriate for use as an input argument. For this reason, input objects have a separate type in the system.

一个输入对象定义了一组输入字段;输入字段是标量、枚举或其他输入对象.这允许参数接受任意复杂的结构.

An Input Object defines a set of input fields; the input fields are either scalars, enums, or other input objects. This allows arguments to accept arbitrarily complex structs.

虽然实现可能提供方便的代码来从单个定义创建对象和相应的输入对象,但在幕后,规范表明它们必须是单独的东西(具有单独的名称,例如 预订ReservationInput).

While an implementation might provide convenience code to create an object and a corresponding input object from a single definition, under the covers, the spec indicates that they'll have to be separate things (with separate names, such as Reservation and ReservationInput).

这篇关于您可以将 graphql 类型设为输入和输出类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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