在GraphQL中的Input和Type之间共享公共字段 [英] Share common fields between Input and Type in GraphQL

查看:1100
本文介绍了在GraphQL中的Input和Type之间共享公共字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种方法可以在GraphQL中的Input和Type之间共享公共字段,这样我就不必在多个地方定义相同的字段集.

I was wondering if there's a way to share the common fields between Input and Type in GraphQL so that I don't have to define the same set of fields in multiple places.

示例:

input PersonInput {
    id: String!
    name: String
    address: String
}

type Person {
    id: String!
    name: String
    address: String
}

我知道Fragment可能是一个解决方案,但是如果我的理解是正确的,那么使用Fragment总是需要您设置一个ON条件,使其看起来像这样:

I know Fragment might be a solution, but if my understanding is correct, using Fragment always requires you to put an ON condition which makes it look like this:

Fragment PersonCommonFields on Person {
    ...
}

似乎无法指定"on Person/PersonInput".

There seems to be no way to specify "on Person/PersonInput".

推荐答案

GraphQL fragments用于查询,而不是架构定义.

GraphQL fragments are for querying, not schema definition.

当我开始学习GraphQL时,我也为此感到恼火,因为我仍在思考RESTful.在大多数情况下,将某些字段设置为不可为空或将它们完全从输入/输出类型中删除的自由是非常宝贵的.

When I started learning GraphQL I was annoyed by this too because I was still thinking RESTfully. In most cases having the freedom to set certain fields non-nullable or remove them entirely from an input/output type is invaluable.

例如

input CreatePersonInput {
  name: String!
  slug: String
  address: String
}

type Person {
  id: ID! # Autogenerated on the server
  name: String!
  slug: String! # Will always exist, either user provided or computed
  # address: String # Omitted for security reasons
}

乍看起来似乎有很多额外的代码,但是对于长期项目而言,这种带给您基于资源的模式的灵活性是值得的.我看过数十次.

It may seem like a lot of extra code at first, but the flexibility this brings you over resource based schemas is worth it for long-term projects. I've seen it help out dozens of times.

您还应该考虑resourcebehavior/task-based突变="noreferrer">贫血突变"

You should also consider behavior/task-based mutations over resource or "anemic mutations"

我强烈建议您学习胖查询和阅读有关继电器规范的信息.即使您最终不想在客户端上使用中继,遵循他们的一些规则也可以真正消除对GraphQL的常见误解.

I highly recommend learning about fat queries and read about Relay Specification. Even if you don't end up wanting Relay on the client, following some of their rules can really clear up common misconceptions about GraphQL.

这篇关于在GraphQL中的Input和Type之间共享公共字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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