GraphQL mutation that accepts an array of dynamic size and common scalar types in one request

octohedron picture octohedron · Nov 19, 2016 · Viewed 48.6k times · Source

I need to be able to create a user and add it's favourite movies (An array of objects with a reference to the Movies collection and his personal rating for each movie) in a single request.

Something that could look like this (pseudocode)

var exSchema = `
 type Mutation {
    addUser(
        name: String!
        favMovies: [{ movie: String! #ref to movies coll
                      personal_rating: Int! # this is different for every movie
                   }]
    ) : User
 }
...
`

What is the graphql way of doing this in a single request? I know I can achieve the result with multiple mutations/requests but I would like to do it in a single one.

Answer

octohedron picture octohedron · Jan 5, 2017

You can pass an array like this

var MovieSchema = `
  type Movie {
   name: String
  }
  input MovieInput {
   name: String
  }
  mutation {
   addMovies(movies: [MovieInput]): [Movie]
  }
`

Then in your mutation, you can pass an array like

mutation {
  addMovies(movies: [{name: 'name1'}, {name: 'name2'}]) {
    name
  }
}

Haven't tested the code but you get the idea