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.
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.
First, let's define the TypeScript code for the GraphQL schema:
TypeScript1import { 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
, andauthor
. - Query Type: The
books
query takes two optional arguments:limit
andoffset
, returning an array ofBook
.
Resolvers are functions that handle fetching data when a field is queried. Here’s how to add the pagination logic:
TypeScript1const 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
: Thebooks
resolver function takes two optional arguments,limit
andoffset
, with default values of 10 and 0, respectively.slice
Method: The resolver uses theslice
method on thebooks
array to return a portion of the array, effectively providing paginated results.
Let's configure and start the Apollo Server 4 instance to serve our GraphQL API:
TypeScript1const 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
andresolvers
. - Server Start: Utilizes
startStandaloneServer
to initiate the server on port 4000.
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:
TypeScript1import 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:
TypeScript1const 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 takeslimit
andoffset
as parameters to fetch a specific range of books. - We define the GraphQL URL and variables — parameters
limit
andoffset
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.
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!