0

I have an object input and want to pass it to mutation:

export enum RatingType {
  GENERAL = 'GENERAL',
  ADULT = 'ADULT',
}
const input = {
  id: '123456789',
  name: 'yourname',
  ratingType: RatingType.ADULT
}

How to pass input into mutation like this:

mutation = `mutation updateUser{
  user: {
     id: "1234567890",
     name: "yourname",
     ratingType: ADULT,
  }
}` 

i tried as below

import {request} from 'graphql-request';
const mutation = `mutation updateUser{
  user: {
     ${JSON.stringify(input)}
  }
}`
const response = await request('http://localhost:3002/graphql', mutation);

but mutation doesn't recognize:

"id" must be id

"name" must be name

"ratingType" must be ratingType

'123456789' must be "123456789"

'yourname' must be "yourname"

'ADULT' must be ADULT

Please give me advice

Thanks.

1 Answer 1

1

First of all, GraphQL is not JSON. So it makes no sense to use JSON.stringify here. In GraphQL you can use variables for your arguments to solve your problem. Then you can provide your variables in JSON format.

Without knowing what library you are using I'm assuming that you communicate with your graphql server without any graphql library. I'm assuming that you use something similar to fetch.

I guess you have something like UpdateUserInput as a graphql type for your input argument. So to use variables you need to rewrite your mutation like the following:

mutation UpdateUser($input: UpdateUserInput) {
  updateUser(user: $user) {
    id
    name
  }
}

Then you can provide your variables like this:

input: JSON.stringify(input)

So the full fetch call will look something like this

const data = {
  query: `
    mutation ($input: UpdateUserInput) {
      updateUser(user: $user) {
        id
        name
      }
    }
  `,
  variables: {
    user: input
  }
};
fetch(url, {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify(data),
});

But it is hard to say how to implement it correctly without knowing your GraphQL client library. Maybe you'll want to have a look at ApolloClient.

Also please keep in mind that I didn't test this code, so there might be some minor errors.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.