Search code examples
node.jsexpressgraphqlexpress-graphql

How to receive an array as member of an input parameter of a GraphQL service?


Given this schema:

input TodoInput {
  id: String
  title: String
}

input SaveInput {
  nodes: [TodoInput]
}

type SavePayload {
  message: String!
}

type Mutation {
  save(input: SaveInput): SavePayload
}

Given this resolver:

type TodoInput = {
  id: string | null,
  title: string
}

type SaveInput = {
  nodes: TodoInput[];
}

type SavePayload = {
  message: string;
}

export const resolver = {
  save: (input: SaveInput): SavePayload => {
    input.nodes.forEach(todo => api.saveTodo(todo as Todo));
    return { message : 'success' };
  }
}

When I sent this request:

mutation {
  save(input: {
    nodes: [
      {id: "1", title: "Todo 1"}
    ]
  }) {
    message
  }
}

Then the value for input.nodes is undefined on the server side.

Does anybody knows what am I doing wrong?

Useful info:

  • The mutation works properly with scalar values (such as String as input and return)
  • I'm using typescript, express and express-graphql.

Solution

  • You need to make changes in the key in the resolver,

    export const resolver = {
      save: (args: {input: SaveInput}): SavePayload => {
        args.input.nodes.forEach(todo => api.saveTodo(todo as Todo));
        return { message : 'success' };
      }
    }