简体   繁体   English

Apollo GraphQL 变量参数名称

[英]Apollo GraphQL variable argument name

Background: I have built a data grid with cell editing on the frontend.背景:我在前端构建了一个带有单元格编辑的数据网格。 Everytime you edit a field in a cell, it is instantly updated on the server.每次编辑单元格中的字段时,它都会立即在服务器上更新。 So I thought it would be a good practice to only submit that single field in my mutation.所以我认为在我的突变中只提交那个单一字段是一个很好的做法。 This would reduce network traffic size and the backend would process the update faster (this is all optimization on a very high level of course).这将减少网络流量大小,后端将更快地处理更新(当然,这是非常高水平的优化)。

This means the argument that I send with my GraphQL mutation is variable.这意味着我随 GraphQL 突变发送的参数是可变的。 You can very nicely inject argument values through GraphQL variables, but what is a good way for the keys?你可以通过 GraphQL 变量很好地注入参数值,但是键的好方法是什么?

To visualize the problem, this is something I'd wish for:为了形象化这个问题,这是我想要的:

mutation($id: 1, $field: "first_name", $value: "John") {
    updateClient(
        id: $id,
        $field: $value
    ) {
        id
    }
}

No, unfortunately argument names cannot be variable in a query.不,不幸的是,参数名称在查询中不能是可变的。 The convention is to use an input object type for mutations to circumvent this problem:约定是使用输入对象类型进行突变来规避这个问题:

type Mutation {
    updateClient(id: ID!, input: ClientInput!): Client
}
input ClientInput {
    a: String
    b: Number
    …
}

(instead of updateClient(id: ID!, a: String, b: Number, …) ) (而不是updateClient(id: ID!, a: String, b: Number, …)

With this pattern, you can pass an object of type ClientInput to your mutation as the argument:使用此模式,您可以将ClientInput类型的对象作为参数传递给您的突变:

query(`mutation($id: ID!, $input: ClientInput!) {
    updateClient(id: $id, input: $input) {
        id
    }
}`, {id: 1, input: {["first_name"]: "John"}})

I really wish there was some kind of argument spread syntax in GraphQL to make this nesting unncessary.我真的希望 GraphQL 中有某种参数传播语法,以使这种嵌套变得不必要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM