typescript 47 lines · 7 steps

Building safe pagination metadata in TypeScript

A pure function turns raw pagination inputs into a fully-derived, bounds-checked metadata object.

Explained by highlit
1interface PaginationParams {
2 totalItems: number;
3 pageSize: number;
4 currentPage: number;
5}
6 
7interface PaginationMeta {
8 currentPage: number;
9 pageSize: number;
10 totalItems: number;
11 totalPages: number;
12 hasPreviousPage: boolean;
13 hasNextPage: boolean;
14 previousPage: number | null;
15 nextPage: number | null;
16 firstItemIndex: number;
17 lastItemIndex: number;
18}
19 
20export function buildPaginationMeta({
21 totalItems,
22 pageSize,
23 currentPage,
24}: PaginationParams): PaginationMeta {
25 const safePageSize = Math.max(1, Math.floor(pageSize));
26 const totalPages = Math.max(1, Math.ceil(totalItems / safePageSize));
27 const page = Math.min(Math.max(1, Math.floor(currentPage)), totalPages);
28 
29 const hasPreviousPage = page > 1;
30 const hasNextPage = page < totalPages;
31 
32 const firstItemIndex = totalItems === 0 ? 0 : (page - 1) * safePageSize + 1;
33 const lastItemIndex = Math.min(page * safePageSize, totalItems);
34 
35 return {
36 currentPage: page,
37 pageSize: safePageSize,
38 totalItems,
39 totalPages,
40 hasPreviousPage,
41 hasNextPage,
42 previousPage: hasPreviousPage ? page - 1 : null,
43 nextPage: hasNextPage ? page + 1 : null,
44 firstItemIndex,
45 lastItemIndex,
46 };
47}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Sanitizing inputs at the top of a function lets the rest of the logic assume clean values.
  2. 2Deriving every output field from a few validated numbers keeps pagination state internally consistent.
  3. 3Explicit interfaces for both input and output make a function's contract self-documenting.

Related explainers

typescript
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { ConfigService } from '@nestjs/config';

How a JWT strategy authenticates in NestJS

authentication jwt passport
Intermediate 7 steps
typescript
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http';
import { BehaviorSubject, Observable, throwError } from 'rxjs';
import { catchError, filter, take, switchMap } from 'rxjs/operators';

Refreshing auth tokens in an Angular interceptor

http-interceptor token-refresh rxjs
Advanced 8 steps
java
@Repository
public interface OrderRepository extends JpaRepository<Order, Long> {
 
    @Query("""

Keyset pagination with Spring Data JPA

pagination cursor jpa
Advanced 8 steps
typescript
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';

How a GraphQL auth guard works in NestJS

authentication authorization jwt
Intermediate 7 steps
typescript
type ResizeCallback = (size: { width: number; height: number }) => void;
 
export function observeResize(callback: ResizeCallback, delay = 150) {
  let timeoutId: ReturnType<typeof setTimeout> | undefined;

Debouncing window resize in TypeScript

debounce closures event-listeners
Intermediate 6 steps
typescript
import { Injectable, Logger, OnApplicationShutdown } from '@nestjs/common';
import { InjectRedis } from '@nestjs-modules/ioredis';
import Redis from 'ioredis';
import { DataSource } from 'typeorm';

Graceful shutdown hooks in NestJS

graceful-shutdown lifecycle-hooks dependency-injection
Intermediate 7 steps

Share this explainer

Here's the card — post it anywhere.

Building safe pagination metadata in TypeScript — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code