Lesson 2
Pagination in GraphQL
Introduction

Welcome to another GraphQL lesson that now focuses on pagination, a critical concept for handling large datasets efficiently.

Pagination is the technique of dividing a dataset into discrete pages, allowing clients to request data in manageable chunks instead of all at once. This improves performance, reduces bandwidth, and provides a better user experience.

Defining the GraphQL Schema with Pagination

First, let's define the TypeScript code for the GraphQL schema:

TypeScript
1import { ApolloServer, gql } from 'apollo-server'; 2 3const typeDefs = gql` 4 type Book { 5 id: ID! 6 title: String! 7 author: String! 8 } 9 10 type Query { 11 books(limit: Int, offset: Int): [Book] 12 } 13`;

Here:

  • Book Type: It has three fields: id, title, and author.
  • Query Type: The books query takes two optional arguments: limit and offset, returning an array of Book.
Implementing Resolvers with Pagination Logic

Resolvers are functions that handle fetching data when a field is queried. Here’s how to add the pagination logic:

TypeScript
1const books = Array.from({ length: 50 }, (_, i) => ({ 2 id: String(i + 1), 3 title: `Book ${i + 1}`, 4 author: `Author ${i + 1}` 5})); 6 7const resolvers = { 8 Query: { 9 books: (_: unknown, { limit = 10, offset = 0 }: { limit?: number; offset?: number }) => books.slice(offset, offset + limit) 10 } 11};

Here:

  • books Array: An array of 50 sample book objects is created for demonstration purposes.
  • Query Resolver: The books resolver function takes two optional arguments, limit and offset, with default values of 10 and 0, respectively.
  • slice Method: The resolver uses the slice method on the books array to return a portion of the array. The slice method takes two parameters: the starting index (offset) and the ending index (offset + limit). This effectively returns a subset of books based on the specified limit and offset, allowing for paginated results.
Fetching Paginated Data from the Client

We will make client-side requests to fetch paginated data using node-fetch. Here is how we can make paginated queries:

First, we define the query:

TypeScript
1import fetch from 'node-fetch'; 2 3const query = ` 4 query getBooks($limit: Int, $offset: Int) { 5 books(limit: $limit, offset: $offset) { 6 id 7 title 8 author 9 } 10 } 11`;

Then, we define our pagination variable and fetch the data:

TypeScript
1const url = 'http://localhost:4000/'; 2 3const variables = { 4 limit: 5, 5 offset: 0 6}; 7 8fetch(url, { 9 method: 'POST', 10 headers: { 11 'Content-Type': 'application/json', 12 }, 13 body: JSON.stringify({ 14 query, 15 variables 16 }), 17}) 18 .then((response) => response.json()) 19 .then((data) => console.log(JSON.stringify(data, null, 2))) 20 .catch((error) => console.error('Error:', error));

Let's quickly understand how it works:

  • We define a GraphQL query getBooks that takes limit and offset as parameters to fetch a specific range of books.
  • We define the GraphQL URL and variables - parameters limit and offset to control pagination.
  • We use fetch to send a POST request to the GraphQL server with the query and variables.
  • The response is received in JSON format, parsed, and then logged to the console.
Lesson Summary

You've now learned:

  • What Pagination Is: Dividing data into discrete pages for performance and user experience.
  • GraphQL Basics: Creating a schema and implementing resolvers with Apollo Server.
  • Running and Querying: Starting the Apollo server and fetching paginated data from the client.

Next, you’ll practice these concepts through exercises. Try adjusting limit and offset values to get different sets of data. Congratulations on completing the lesson and the course! The skills you’ve learned are valuable for creating efficient and flexible APIs using GraphQL. Well done!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.