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:
id
, title
, and author
.books
query takes two optional arguments: limit
and offset
, returning an array of Book
.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
: 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.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:
getBooks
that takes limit
and offset
as parameters to fetch a specific range of books.limit
and offset
to control pagination.fetch
to send a POST request to the GraphQL server with the query and variables.You've now learned:
Apollo Server
.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!