7 min read
Original source

Offset and keyset pagination with Kysely

So far, when working with Kysely, we fetched all rows from our tables. However, this might not be the best solution when it comes to performance. A common…

So far, when working with Kysely, we fetched all rows from our tables. However, this might not be the best solution when it comes to performance. A common approach is to query the data in parts and present the users with separate pages or infinite scrolling. We implement pagination in this article with NestJS, PostgreSQL, and Kysely to achieve that. While doing that, we compare various solutions and point out their pros and cons. Offset and limit First, let’s look at the result of a simple SELECT query.const databaseResponse = await this.database .selectFrom('articles') .selectAll() .execute();It queries all rows from the articles table. The crucial thing about the above results is that the order of the returned records is not guaranteed. However, when implementing pagination, we need the order to be predictable. Therefore, we have to sort the results.const databaseResponse = await this.database .selectFrom('articles') .orderBy('id') .selectAll() .execute(); The first step in implementing pagination is to limit the number of rows in the result. To do that, we need the limit() function.const databaseResponse = await this.database .selectFrom('articles') .orderBy('id') .limit(5) .selectAll() .execute(); Thanks to the above, we now get only five elements instead of the whole contents of the articles table. By doing that, we get the first page of the results. To get to the second page, we must skip a certain number of rows. To achieve that, we need the offset() function.const databaseResponse = await this.database .selectFrom('articles') .orderBy('id') .limit(5) .offset(5) .selectAll() .execute(); Above, we omit the first five rows and get the five next rows in return thanks to combining the limit() and offset() functions. In this case, it gives us the rows with IDs from 6 to 10. It is crucial to maintain a steady order of rows when traversing through various pages of data to avoid skipping some rows or showing some of them more than once. Counting the number of rows It is a common feature to present the number of data pages to the user. For example, if we have a hundred rows and show ten per page, we have ten data pages. To determine that, we need to know the number of rows in the table. To do that, we need the count() function.const { count } = await this.database .selectFrom('articles') .select((expressionBuilder) => { return expressionBuilder.fn.countAll().as('count'); }) .executeTakeFirstOrThrow();It is crucial to count the rows in the database in the same transaction as the query that gets the data. This way, we ensure the consistency of our results. If you want to know more about transactions with Kysely, check out API with NestJS #123. SQL transactions with Kysely const databaseResponse = await this.database .transaction() .execute(async (transaction) => { const articlesResponse = await transaction .selectFrom('articles') .orderBy('id') .limit(5) .offset(5) .selectAll() .execute(); const { count } = await transaction .selectFrom('articles') .select((expressionBuilder) => { return expressionBuilder.fn.countAll().as('count'); }) .executeTakeFirstOrThrow(); return { data: articlesResponse, count, }; }); Offset pagination with NestJS When implementing the offset pagination with a REST API, we expect the users to provide the offset and limit as query parameters. Let’s create a designated class to handle that. paginationParams.ts import { IsNumber, Min, IsOptional } from 'class-validator'; import { Type } from 'class-transformer'; export class PaginationParams { @IsOptional() @Type(() => Number) @IsNumber() @Min(0) offset: number = 0; @IsOptional() @Type(() => Number) @IsNumber() @Min(1) limit: number | null = null; } To read more about validation in NestJS, read API with NestJS #4. Error handling and data validation We can now use the above class in our controller to validate the offset and limit parameters. articles.controller.ts import { Controller, Get, Query, UseInterceptors, ClassSerializerInterceptor, } from '@nestjs/common'; import { ArticlesService } from './articles.service'; import { GetArticlesByAuthorQuery } from './getArticlesByAuthorQuery'; import { PaginationParams } from './dto/paginationParams.dto'; @Controller('articles') @UseInterceptors(ClassSerializerInterceptor) export class ArticlesController { constructor(private readonly articlesService: ArticlesService) {} @Get() getAll( @Query() { authorId }: GetArticlesByAuthorQuery, @Query() { offset, limit }: PaginationParams, ) { return this.articlesService.getAll(authorId, offset, limit); } // ... }The last step is to implement the offset and limit pagination in our repository. articles.repository.ts import { Database } from '../database/database'; import { Article } from './article.model'; import { Injectable } from '@nestjs/common'; @Injectable() export class ArticlesRepository { constructor(private readonly database: Database) {} async getAll(offset: number, limit: number | null) { const { data, count } = await this.database .transaction() .execute(async (transaction) => { let articlesQuery = transaction .selectFrom('articles') .orderBy('id') .offset(offset) .selectAll(); if (limit !== null) { articlesQuery = articlesQuery.limit(limit); } const articlesResponse = await articlesQuery.execute(); const { count } = await transaction .selectFrom('articles') .select((expressionBuilder) => { return expressionBuilder.fn.countAll().as('count'); }) .executeTakeFirstOrThrow(); return { data: articlesResponse, count, }; }); const items = data.map((articleData) => new Article(articleData)); return { items, count, }; } // ... }Thanks to the above approach, we get a full working offset-based pagination. Advantages The offset-based pagination is a very common approach that is straightforward to implement. When using it, the user can easily skip multiple data pages at once. It also makes it easy to change the columns we use when sorting. Therefore, it is a good enough solution in many cases. Disadvantages Unfortunately, the offset-based pagination has significant disadvantages. The most important one is that the database must compute all rows skipped through the offset. This can hurt our performance: the database sorts all rows according to the specified order, then, it drops the number of rows defined in the offset. Aside from that, we can experience issues with a lack of consistency: the user number one fetches the first page with articles, the user number two creates a new article that ends up on the first page, the user number one fetches the second page. The above situation causes user number one to miss the new article added to the first page. They also see the last element from the first page again on the second page. Keyset pagination An alternative approach to pagination involves filtering the data with the where() function instead of the offset(). Let’s consider the following query:const databaseResponse = await this.database .selectFrom('articles') .orderBy('id') .limit(5) .selectAll() .execute(); In the above results, we can see that the last row has an ID of 5. We can use this information to query articles with an ID bigger than 5.const databaseResponse = await this.database .selectFrom('articles') .orderBy('id') .where('id', '>', 5) .limit(5) .selectAll() .execute(); We should use the same column both for odering and for filtering with the where() function. To get the next chunk of results, we need to look at the results and notice that the id of the last row is 10. We can use that when calling the where() function. This exposes the most significant disadvantage of the keyset pagination, unfortunately. To get the next data page, we need to know the ID of the last element of the previous page. Because of that, we can’t traverse more than one page at once. Keyset pagination with NestJS To implement the keyset pagination with NestJS, we need to start by accepting an additional query parameter. paginationParams.ts import { IsNumber, Min, IsOptional } from 'class-validator'; import { Type } from 'class-transformer'; export class PaginationParams { @IsOptional() @Type(() => Number) @IsNumber() @Min(0) offset: number = 0; @IsOptional() @Type(() => Number) @IsNumber() @Min(1) limit: number | null = null; @IsOptional() @Type(() => Number) @IsNumber() @Min(0) idsToSkip: number = 0; }We can now modify our repository and use the above parameter. articles.repository.ts import { Database } from '../database/database'; import { Article } from './article.model'; import { Injectable } from '@nestjs/common'; @Injectable() export class ArticlesRepository { constructor(private readonly database: Database) {} async getAll(offset: number, limit: number | null, idsToSkip: number) { const { data, count } = await this.database .transaction() .execute(async (transaction) => { let articlesQuery = transaction .selectFrom('articles') .where('id', '>', idsToSkip) .orderBy('id') .offset(offset) .selectAll(); if (limit !== null) { articlesQuery = articlesQuery.limit(limit); } const articlesResponse = await articlesQuery.execute(); const { count } = await transaction .selectFrom('articles') .select((expressionBuilder) => { return expressionBuilder.fn.countAll().as('count'); })

Offset and keyset pagination with Kysely | NestJS.io