【问题标题】:Reusing input type as fragment in GraphQL [duplicate]在 GraphQL 中重用输入类型作为片段 [重复]
【发布时间】:2019-02-26 09:50:16
【问题描述】:

GraphQL 中一个非常常见的用例是创建具有突变的对象,并接收完全相同的字段,以及数据库返回的 ID。这是一个相关的question 询问这个问题。

我的问题是,如何简化这种模式以避免重复字段?我尝试将输入类型作为片段重用,

input ClientInput {
  short_name: String
  full_name: String
  address: String
  email: String
  location: String  
}

type Client {
  id: String
  ...ClientInput
}

...但是失败了

语法错误:预期名称,找到...

我在 Fragments 上看到的所有 documentation 和博客文章总是将它们 on 创建为现有类型。这意味着仍然重复除了 ID 字段之外的所有内容:

type Client {
  _id: String
  short_name: String
  full_name: String
  address: String
  email: String
  location: String
}

fragment ClientFields on Client {
  short_name: String
  full_name: String
  address: String
  email: String
  location: String
}

input ClientInput {
  ...ClientFields
}

这样更好吗?

【问题讨论】:

    标签: types graphql


    【解决方案1】:

    TL;DR: 允许在对象类型和输入对象类型之间共享字段的机制只是不存在。在编写查询时,片段只能在客户端使用。

    来自规范:

    片段允许重复使用常见的重复选择字段,减少文档中的重复文本。

    片段背后的意图是,您可能保存了任意数量的查询相同类型的查询 - 如果架构发生更改或您决定不需要某个特定的查询,您不希望更新 20 个不同的查询字段了。

    一种允许在服务器端类型和输入类型之间共享字段的类似机制只是不存在。这可能很大程度上是设计使然,因为即使 Type 字段和 Input Type 字段都具有某种type,它们也可能具有其他属性。例如,输入类型字段可以具有默认值,而类型字段不存在该属性。同样,Type 字段具有解析器和参数,而 Input Type 字段没有。

    如果您真的想保持 DRY,则可能有可用的解决方法,具体取决于您运行的 GraphQL 服务器类型。例如,如果它是使用从一个或多个 SDL 字符串创建的模式的 GraphQL.js 服务器,则可以只使用模板文字:

    const sharedClientFields = `
        short_name: String
        full_name: String
        address: String
        email: String
        location: String 
    `
    const schema = `
      type Client {
        _id: String
        ${sharedClientFields}
      }
    
      type ClientInput {
        ${sharedClientFields}
      }
    `
    

    【讨论】:

    • 感谢您的回答!既然我的问题被证明是一个骗子,你想把这个答案移到原来的问题上吗?
    猜你喜欢
    • 2018-09-19
    • 2019-07-09
    • 2021-06-09
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 1970-01-01
    • 2021-09-10
    • 2014-02-13
    相关资源
    最近更新 更多