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.
First, let's define the TypeScript code for the GraphQL schema:
TypeScript1import { 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
, 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. Theslice
method takes two parameters: the starting index (offset
) and the ending index (offset + limit
). This effectively returns a subset of books based on the specifiedlimit
andoffset
, allowing for paginated results.
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 received 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
. - 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!