Kest

Search

Search the documentation

GraphQL

Mutations

Change data, and return what changed.

A query reads; a mutation changes data. Technically a mutation is a query that you promise has side effects: GraphQL runs several mutations in a request one after the other, queries may run in parallel.

input NewOrder { sku: String!  quantity: Int! }
type Mutation {
  placeOrder(input: NewOrder!): Order!
  cancelOrder(id: ID!): Order!
}
data class NewOrder(@field:NotBlank val sku: String, @field:Min(1) val quantity: Int)
 
@Resolver
class OrderMutations(private val orders: OrderService) {
    @Authenticated @Mutation
    fun placeOrder(input: NewOrder): Order = orders.place(input)       // the SDL input type is decoded into NewOrder, and validated
 
    @Authenticated @Roles("admin") @Mutation
    fun cancelOrder(id: String): Order = orders.cancel(id)
}
mutation { placeOrder(input: { sku: "A1", quantity: 2 }) { id total status } }

Design rules that save pain later

  • One input object per mutation (input: NewOrder!) rather than a long list of arguments: adding a field later does not break clients.
  • Return the changed object, so the client can update its screen from the response without asking again.
  • Name by action (placeOrder, cancelOrder), not updateOrder for everything.
  • Validation works as on controllers: annotations on the input class are checked and a failure is a BAD_USER_INPUT error with details.
  • Group writes that must succeed together in @Transactional (Transactions); announce them with the outbox.
  • Make mutations that clients may retry idempotent: accept a client-chosen id, or an idempotency key.

Errors in mutations

Throw the usual exceptions; they become GraphQL errors with a code (Resolvers). For expected outcomes (an out-of-stock item) consider returning a union instead, so the client handles it like data:

union PlaceOrderResult = Order | OutOfStock
type OutOfStock { sku: String!  available: Int! }

See Interfaces and Unions and Enums.

Read more