[SOLVED] How to specify Graphql mutation with object variable when making Fetch call?

Issue

This Content is from Stack Overflow. Question asked by John

I have a Graphql schema that looks like this:

type Mutation {
  createUploadUrl(
    input: CreateUploadUrl!
  ): MyResponse!
}

input CreateUploadUrl {
  deploymentId: ID!
}

I’m new to Graphql and am getting lost when trying to work out what my query should look like when I submit it via fetch:

fetch('https://example.com', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({
        query: `
            mutation($input: ) {
               createUploadUrl($input) {
                 __typename,
                 // my values I want to retrieve
                 // ...
               }
             }`,
        variables: {
            input: {deploymentId: "XXX"}
        }
    }),
})
    .then((res) => res.json())
    .then((result) => console.log(result));

The above gives me an error: `message: “Syntax Error: Expected Name, found “$”.”

How am I supposed to specify a query or mutation that requires an object as a variable?
`



Solution

You just need to define your parametrized function and wrap the effective mutation.
In the example below the mutation MyMutation takes as param a $arg wich is a CreateUploadUrl!.
Then pass the $arg to the input of the mutation, the invocation becomes:

mutation MyMutation($arg: CreateUploadUrl!) {
  createUploadUrl(input: $arg) {
  __typename,
  ...
}


This Question was asked in StackOverflow by John and Answered by dna It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?