Advanced Arguments in GraphQL with Apollo Server 4

Introduction and Overview

In this lesson, we will build upon your existing GraphQL skills by introducing advanced query and mutation arguments. These techniques will enable you to create more flexible and powerful APIs. Advanced arguments allow for better precision in the data you request and the operations you perform.

Defining Advanced Schema with Arguments

Let's start by defining our GraphQL schema. The schema is a blueprint for the structure of your API.

Below is the schema we will use:

const typeDefs = `#graphql
  type Book {
    id: ID!
    title: String!
    author: String!
    publishedDate: String
    genre: String
  }

  type Query {
    books(genre: String, author: String): [Book]
  }

  type Mutation {
    addBook(title: String!, author: String!, publishedDate: String, genre: String): Book
  }
`;

export { typeDefs };

In this schema:

  • The Book type defines the structure of a book object.
  • The Query type has a books field that accepts two optional arguments, genre and author, to filter books.
  • The Mutation type has an addBook field that accepts arguments to add a new book to our dataset.

Resolvers: Filtering Data with Query Arguments

Resolvers fetch the data specified in the schema. Here, we will write resolvers to handle the books query with filtering capabilities:

import { v4 as uuidv4 } from 'uuid';

const books = [
  { id: '1', title: 'The Hobbit', author: 'J.R.R. Tolkien', publishedDate: '1937', genre: 'Fantasy' },
  { id: '2', title: '1984', author: 'George Orwell', publishedDate: '1949', genre: 'Dystopian' },
  // More books...
];

const resolvers = {
  Query: {
    books: (_: unknown, { genre, author }: { genre?: string; author?: string }) => {
      return books.filter(book =>
        (genre ? book.genre === genre : true) &&
        (author ? book.author === author : true)
      );
    }
  },
  Mutation: {
    addBook: (_: unknown, { title, author, publishedDate, genre }: { title: string; author: string; publishedDate: string; genre: string }) => {
      const newBook = { id: uuidv4(), title, author, publishedDate, genre };
      books.push(newBook);
      return newBook;
    }
  }
};

export { resolvers };

In this resolver:

  • The books query accepts genre and author as optional arguments.
  • It filters the books array based on these arguments.
  • If an argument is provided, it filters by that argument; otherwise, it includes all books.

Notice how we use the uuidv4 function to generate a unique identifier for each new book added to the dataset. This ensures that every book has a distinct ID, which is crucial for identifying and managing individual entries in the database.

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