How to deal with nested input in GraphQL

Skyler Richter picture Skyler Richter · Sep 2, 2018 · Viewed 7.4k times · Source

When writing queries I can define a resolver on any field and that field’s value will be determined by its resolver, regardless of query depth.

However when writing a mutation I seem to only be able to define the resolvers at the root level. Adding a resolve method to fields in my args or input type does not seem to have any affect.

What’s the best way deal with nested input in mutations?

Answer

David Mraz picture David Mraz · Sep 3, 2018

What do you mean by nested input in your mutations? GraphQL input types does not have resolvers. With resolvers you are just determining how to fetch results. If you would like to have nested input, e.g. for example I would like to create user also with company. I will then define CreateUserInput CreateCompanyInput type for example like this in SDL

input CreateCompanyInput {
   name: String!
   type: CompanyEnum!
}

input CreateUserInput { 
  username: String!
  firstname: String!
  lastname: String!
  company: CreateCompanyInput!
}

type Mutation {
  createUser(input: CreateUserInput!): User
}

This way I am basically nesting arguments and can implement more complex mutations. In addition I can reuse the CreateCompanyInput for createCompany mutation if I need mutation even for that. I will then have the whole CreateUserInput even with CreateCompanyInput in the createUser resolver as input argument. I can apply transactions as I will create two new records etc. Not sure if it is what you mean by nested input if you mean something else. Just let me know :)