Cutaraca
Cutaraca

Reputation: 2479

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. You can very nicely inject argument values through GraphQL variables, but what is a good way for the keys?

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
    }
}

Upvotes: 2

Views: 1042

Answers (1)

Bergi
Bergi

Reputation: 664195

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, …))

With this pattern, you can pass an object of type ClientInput to your mutation as the argument:

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.

Upvotes: 3

Related Questions