Skip to content

REST API with NestJS ​

A variant of chapter 3 of the recipes storyline: the same realm/user API, wired into NestJS. The contract (src/schema.ts) and the codec (src/codec.ts) are reused verbatim; only the HTTP glue changes.

Rapiq needs no Nest module. Two small pieces connect it: a parameter decorator that hands the raw query string to a pipe, and the pipe that decodes it against a schema and turns contract violations into 400s. Controllers then receive a validated IQuery like any other argument. Neither piece knows about the database: the controller hands the query to whichever backend adapter you use (TypeORM, Prisma or Drizzle below).

Project layout ​

txt
src/
├── schema.ts                 # schemas + registry (from chapter 3)
├── codec.ts                  # shared URL codec (from chapter 3)
├── rapiq/
│   ├── query.pipe.ts         # decode + validate, 400 on violations
│   └── query.decorator.ts    # @RapiqQuery('user'), backend-independent
└── users/users.controller.ts # the only backend-specific file

1. The pipe ​

typescript
// src/rapiq/query.pipe.ts
import { BadRequestException, type PipeTransform } from '@nestjs/common';
import { type IQuery, isParseError } from '@rapiq/core';
import { formatErrors } from '@rapiq/codec-url';
import { codec } from '../codec';

export type RapiqInput = {
    query: string,
    context: unknown,
};

export class RapiqQueryPipe implements PipeTransform<RapiqInput, Promise<IQuery>> {
    constructor(protected readonly schema: string) {}

    async transform(input: RapiqInput) : Promise<IQuery> {
        let query : IQuery | null;
        try {
            query = await codec.decodeAsync(input.query, {
                schema: this.schema,
                context: input.context,
            });
        } catch (e) {
            if (isParseError(e)) {
                // every violation of the request, not just the first one
                throw new BadRequestException({
                    errors: formatErrors(e.issues, { status: '400' }),
                });
            }

            throw e;
        }

        if (!query) {
            throw new BadRequestException('Invalid query input.');
        }

        return query;
    }
}

decodeAsync lets the schema's validate hooks be asynchronous (a permission lookup, for example); with synchronous hooks only, decode works the same way. Errors that are not parse errors are rethrown, so a server fault stays a 500 instead of turning into a client error.

2. The decorator ​

typescript
// src/rapiq/query.decorator.ts
import { createParamDecorator, type ExecutionContext } from '@nestjs/common';
import { type RapiqInput, RapiqQueryPipe } from './query.pipe';

const RapiqInputParam = createParamDecorator(
    (_data: unknown, ctx: ExecutionContext) : RapiqInput => {
        const request = ctx.switchToHttp().getRequest();
        const url : string = request.originalUrl ?? request.url;
        const index = url.indexOf('?');

        return {
            query: index === -1 ? '' : url.substring(index + 1),
            // forwarded to the schema validate hooks as the parse context
            context: request.user,
        };
    },
);

export const RapiqQuery = (schema: string) => RapiqInputParam(
    undefined,
    new RapiqQueryPipe(schema),
);

The decorator reads the raw query string rather than @Query(). That keeps decoding independent of the platform's own query parser: Express 5 (the default since Nest 11) parses query strings without bracket nesting unless query parser is set to extended, and Fastify's default parser has no bracket support at all. The codec parses the string itself, so fields[realm]=name decodes the same on every platform.

Replace request.user with whatever your authentication guard attaches to the request; it reaches the schema's validate hooks as context, see Authorization & Scoping.

3. The controller ​

The controller is the only place the backend shows up. The decorator, the pipe and the meta envelope stay identical; only the lines between receiving the query and returning the data change.

typescript
// src/users/users.controller.ts
import { Controller, Get } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import type { Repository } from 'typeorm';
import type { IQuery } from '@rapiq/core';
import { TypeormAdapter } from '@rapiq/adapter-typeorm';
import { RapiqQuery } from '../rapiq/query.decorator';
import { User } from './user.entity';

const adapterConfig = { relations: { joinAndSelect: true } };

@Controller('users')
export class UsersController {
    constructor(
        @InjectRepository(User)
        private readonly repository: Repository<User>,
    ) {}

    @Get()
    async getMany(@RapiqQuery('user') query: IQuery) {
        const queryBuilder = this.repository.createQueryBuilder('user');

        // adapter & builder are per-request; the config object is shared
        const adapter = new TypeormAdapter({ ...adapterConfig, queryBuilder });
        const { pagination } = adapter.execute(query);

        const [data, total] = await queryBuilder.getManyAndCount();

        return {
            data,
            meta: { total, limit: pagination.limit, offset: pagination.offset },
        };
    }
}
typescript
// src/users/users.controller.ts
import { Controller, Get } from '@nestjs/common';
import type { IQuery } from '@rapiq/core';
import { RapiqQuery } from '../rapiq/query.decorator';
import { PrismaService } from '../prisma.service';
// the stateless PrismaAdapter with its metadata, defined as in chapter 4
import { userAdapter } from './user.adapter';

@Controller('users')
export class UsersController {
    constructor(private readonly prisma: PrismaService) {}

    @Get()
    async getMany(@RapiqQuery('user') query: IQuery) {
        const { args, pagination } = userAdapter.execute(query);

        const [data, total] = await Promise.all([
            this.prisma.user.findMany(args),
            // filters, but never the page window: the pre-pagination total
            this.prisma.user.count({ where: args.where }),
        ]);

        return {
            data,
            meta: { total, limit: pagination.limit, offset: pagination.offset },
        };
    }
}
typescript
// src/users/users.controller.ts
import { Controller, Get, Inject } from '@nestjs/common';
import type { IQuery } from '@rapiq/core';
import { RapiqQuery } from '../rapiq/query.decorator';
import { DATABASE, type Database } from '../database';
// the stateless DrizzleAdapter with its metadata, defined as in chapter 4
import { userAdapter } from './user.adapter';

@Controller('users')
export class UsersController {
    constructor(@Inject(DATABASE) private readonly db: Database) {}

    @Get()
    async getMany(@RapiqQuery('user') query: IQuery) {
        const { config, pagination } = userAdapter.execute(query);

        const data = await this.db.query.users.findMany(config);

        // an unsatisfiable filter surfaces as `limit: 0`, see chapter 4
        const impossible = config.limit === 0 && pagination.limit !== 0;
        const total = impossible ?
            0 :
            (await this.db.query.users.findMany({
                where: config.where,
                columns: { id: true },
            })).length;

        return {
            data,
            meta: { total, limit: pagination.limit, offset: pagination.offset },
        };
    }
}

TypeORM's adapter wraps a per-request query builder, so it is constructed inside the handler. The Prisma and Drizzle adapters are stateless serializers: build one per model in a small module (user.adapter.ts) with the metadata and provider options from Swapping the Backend and share it. PrismaService and the DATABASE token stand for however your application provides its Prisma client or Drizzle database.

The registry and the codec are plain module constants, as in chapter 3. They hold no per-request state, so there is nothing to gain from making them Nest providers; wrap them in one only if you want to swap them in tests.

What clients can now do ​

The endpoint behaves exactly like the Express one, on every backend:

txt
GET /users                                            defaults: id+name, sorted -id, limit 50
GET /users?filter[age]=>=18&sort=-age                 filtered & sorted
GET /users?include=realm&fields[realm]=name           relation + sparse fields
GET /users?page[limit]=10&page[offset]=20             paged; a limit above 50 is a 400
GET /users?filter[secret]=x                           400: key not allowed

Variations ​

  • Scope by the authenticated user: the decorator already forwards request.user as the parse context; add server conditions as shown in Authorization & Scoping.
  • Testing without a database: run the same query against fixture arrays with @rapiq/adapter-memory; the decorator and the pipe need no change.
  • Error shape: the pipe returns JSON:API-style errors; if your API has its own error envelope, map e.issues in the pipe or let a Nest exception filter format a rethrown ParseError.

Released under the MIT License.