chapter eight

8 Implementing Mutations

 

This chapter covers:

  • Implementing GraphQL’s mutation fields
  • Sharing payload and input types between mutations
  • Authenticating users for each mutation operation
  • Creating custom user-friendly error messages
  • Using powerful database features to optimize mutations
  • Using dependency injection between related mutation operations
  • Using custom values in ENUM types

We’ve concluded the implementation of the "query" tree for the AZdev GraphQL API in Chapter 7. It’s now time to implement the mutations and subscriptions operations we planned. Starting with the userCreate mutation to enable AZdev users to create an account and use other mutations that require authenticated requests.

Since this is the very first mutation we’re creating, we need to do some groundwork to wire things up for all mutations. We basically need to first make the schema ready to host mutations.

8.1  The mutators Context Object

We’ve abstracted all database READ operations to go through DataLoader instances through the loaders object we passed to each resolver as part of the global GraphQL context. It’s time to think about the WRITE operations. Every mutation operation will perform an INSERT or UPDATE or DELETE SQL statement or MongoDB operation (or combinations of them). These WRITE operations do not need to go through DataLoader. Although we could make the mutations' READ parts go through DataLoader, I think that would be a case of over-engineering. Let’s start simple.

8.2  The Root Mutation Type

8.3  User Mutations:

8.3.1  The userCreate Mutation

8.3.2  The userLogin Mutation

8.4  Need Mutations

8.4.1  The needCreate Mutation

8.4.2  The needUpdate Mutation

8.5  Approach Mutations

8.5.1  The approachCreate Mutation

8.5.2  The approachVote mutation

8.6  Summary