Gato GraphQL logo

Returning different types on mutations

Returning different types on mutations

Mutation fields can be configured to return either of these 2 different entity types:

  • A payload object type
  • Directly the mutated entity

A payload object type contains all the data concerning the mutation:

  • The status of the mutation (success or failure)
  • The errors (if any) using distinctive GraphQL types, or
  • The successfully mutated entity

For instance, mutation updatePost returns an object of type PostUpdateMutationPayload, and we still need to query its field post to retrieve the updated post entity:

mutation UpdatePost {
  updatePost(input: {
    id: 1724,
    title: "New title",
    status: publish
  }) {
    # This is the status of the mutation: SUCCESS or FAILURE
    status
    errors {
      __typename
      ...on ErrorPayload {
        message
      }
    }
    post {
      id
      title
      # This is the status of the post: publish, pending, trash, etc
      status
    }
  }
}

In this mode, the GraphQL schema will contain plenty of additional MutationPayload, MutationErrorPayloadUnion and ErrorPayload types, so it will have a bigger size:

GraphQL schema with payload object types for mutations

With the mutated entity type, the mutation will directly return the mutated entity in case of success, or null in case of failure, and any error message will be displayed in the JSON response's top-level errors entry.

For instance, mutation updatePost will return the object of type Post:

mutation UpdatePost {
  updatePost(input: {
    id: 1724,
    title: "New title",
    status: publish
  }) {
    id
    title
    status
  }
}

Because there are no additional types added, the GraphQL schema will look leaner:

GraphQL schema without payload object types for mutations