Lesson 2
Using Apollo Server 4 for GraphQL Pagination and Enhancing Data Fetching Efficiency
Deprecation Notice

This course path teaches Apollo Server 3, which has been deprecated. To access the new course paths covering Apollo Server 4, use this course path.

Introduction

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

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 } from '@apollo/server'; 2import { startStandaloneServer } from '@apollo/server/standalone'; 3 4const typeDefs = `#graphql 5 type Book { 6 id: ID! 7 title: String! 8 author: String! 9 } 10 11 type Query { 12 books(limit: Int, offset: Int): [Book] 13 } 14`;

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, effectively providing paginated results.
Setting Up and Running the Apollo Server

Let's configure and start the Apollo Server 4 instance to serve our GraphQL API:

TypeScript
1const server = new ApolloServer({ 2 typeDefs, 3 resolvers 4}); 5 6const { url } = await startStandaloneServer(server, { 7 listen: { port: 4000 }, 8}); 9 10console.log(`🚀 Server ready at: ${url}`);

Here:

  • ApolloServer Instance: Created with typeDefs and resolvers.
  • Server Start: Utilizes startStandaloneServer to initiate the server on port 4000.
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 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 4.
  • Running and Querying: Starting the Apollo server and fetching paginated data from the client.

Next, you’ll practice these concepts through exercises. Try adjusting the 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.