GraphQL Mutations with Apollo Server 4 in TypeScript

Introduction

Welcome to the first lesson of our "GraphQL Mutations and Advanced Apollo Server" course, part of the "Comprehensive Intro to GraphQL in TypeScript" series. In this lesson, you'll learn how to add mutations, which will allow you to modify data on the server.

Revisiting Apollo Server Basics

We'll start with a quick review of key components without introducing mutations.

  1. Import Modules: Import the necessary modules, including ApolloServer for setting up the server and uuid for generating unique IDs.

    import { ApolloServer } from '@apollo/server';
    import { startStandaloneServer } from '@apollo/server/standalone';
    import { v4 as uuidv4 } from 'uuid';
  2. Define Schema: Define the GraphQL schema with a Book type and a Query type to fetch book data.

    const typeDefs = `#graphql
      type Book {
        id: ID!
        title: String!
        author: String!
      }
    
      type Query {
        books: [Book]
        book(id: ID!): Book
      }
    `;
  3. Sample Data: Provide some sample book data to be served by our query.

    let books = [
      { id: '1', title: 'The Hobbit', author: 'J.R.R. Tolkien' },
      { id: '2', title: 'Harry Potter', author: 'J.K. Rowling' },
    ];
  4. Define Resolvers: Specify how each field in the schema maps to the data provided.

    const resolvers = {
      Query: {
        books: () => books,
        book: (_: any, args: { id: string }) => books.find(book => book.id === args.id),
      },
    };
  5. Initialize and Start Server: Create an instance of ApolloServer and start it.

    const server = new ApolloServer({
      typeDefs,
      resolvers,
    });
    
    const { url } = await startStandaloneServer(server, {
      listen: { port: 4000 },
    });
    
    console.log(`🚀 Server ready at ${url}`);

Introduction to Mutations

In GraphQL, mutations allow clients to modify data on the server, such as creating, updating, or deleting records. Unlike queries, which are read-only and do not affect the server's state, mutations perform write operations. Mutations often correspond to HTTP POST requests and require specific arguments to specify the data to be modified. They return the updated or deleted data, enabling clients to immediately see the result of their operation.

  1. AddBook Mutation: Define a mutation to add a new book by specifying a title and author.

    type Mutation {
      addBook(title: String!, author: String!): Book
    }
  2. DeleteBook Mutation: Define a mutation to delete a book by specifying its ID.

    type Mutation {
      deleteBook(id: ID!): Book
    }
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal