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

查看:23
本文介绍了在 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 时,我也对此很恼火,因为我仍然在思考 REST.在大多数情况下,能够自由地将某些字段设置为不可为空或将它们从输入/输出类型中完全删除是非常宝贵的.

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.

您还应该考虑 behavior/task-basedresource贫血突变"

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

我强烈建议您了解胖查询和阅读继电器规范.即使您最终不想在客户端上使用 Relay,遵循他们的一些规则也可以真正消除对 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天全站免登陆