Passing Objects as Argument to GraphQL Mutation (graphql-request)

7k views Asked by At

I have a very basic graphql mutation in the frontend that I send to my backend. I am using this code on the by graphql-request as a guide.

With primitives it works:

const mutation = gql`
    mutation EditArticle($id: ID!, $title: String) {
      editArticle(id: $id, title: $title) {
        id
      }
    }
  `

Now I'd like to also be able to mutate some meta data about the article, stored in a meta object inside the article:

...,
title: "Hello World",
meta: {
 author: "John",
 age: 32,
 ...
}

So my question is: How do I pass over non-primitive object types as arguments to mutations when making the request from the frontend, using graphql-request?

I tried something like this already:

const Meta = new GraphQLObjectType({
    name: "Meta",
    fields: () => ({
      id: { type: GraphQLID },
      name: { type: GraphQLString },
      age ....
    }),
  })
   
const mutation = gql`
    mutation EditArticle($id: ID!, $title: String, $meta: Meta) { //??? I don't seem to get what goes here? 
      editArticle(id: $id, title: $title, meta: $meta) {
        id
      }
    }
  `

I also tried it with GraphQLObjectType, but I think I am going wrong here (since this is the frontend).

PS: I looked at this answer, but I didn't understand / believe the solution there might be incomplete.

1

There are 1 answers

1
Bergi On BEST ANSWER

You need to define the input object type in your serverside schema, as something like

input MetaInput {
  name: String
  author: String
  release: Date
}

and use it in the editArticle definition

extend type Mutation {
  editArticle(id: ID!, title: String, meta: MetaInput): Article
}

Then you can also refer to the MetaInput type in the clientside definition of your mutation EditArticle.