|
| 1 | +--- |
| 2 | +name: '@nest-openapi/serializer' |
| 3 | +description: High-performance response serialization for NestJS based on your OpenAPI spec using fast-json-stringify. |
| 4 | +categories: |
| 5 | + - misc |
| 6 | +link: https://nest-openapi.github.io/serializer/ |
| 7 | +languages: |
| 8 | + typescript: true |
| 9 | + nodejs: true |
| 10 | +repo: https://github.com/ts-oas/nest-openapi |
| 11 | +oasVersions: |
| 12 | + v2: false |
| 13 | + v3: true |
| 14 | + v3_1: true |
| 15 | + v3_2: false |
| 16 | +--- |
| 17 | + |
| 18 | +## Overview |
| 19 | + |
| 20 | +`@nest-openapi/serializer` provides high-performance response serialization for NestJS applications. It uses `fast-json-stringify` to automatically serialize responses according to your OpenAPI specification, ensuring output matches your API contract while maintaining optimal performance. |
| 21 | + |
| 22 | +## Features |
| 23 | + |
| 24 | +- **Spec-driven**: Automatically serializes responses based on your OpenAPI schema definitions |
| 25 | +- **Fast by default**: Uses [`fast-json-stringify`](https://github.com/fastify/fast-json-stringify) with caching and optional pre‑compilation. |
| 26 | +- **NestJS‑native**: Auto serializes with per‑route opt‑out and overrides. |
| 27 | +- **Drop-in integration**: Works seamlessly with existing NestJS controllers |
| 28 | +- **Platform agnostic**: Supports both Express and Fastify adapters |
| 29 | + |
| 30 | +## Usage |
| 31 | + |
| 32 | +Install the package and configure it in your NestJS module: |
| 33 | + |
| 34 | +```typescript |
| 35 | +import { OpenAPISerializerModule } from '@nest-openapi/serializer'; |
| 36 | +import { Module } from '@nestjs/common'; |
| 37 | + |
| 38 | +import * as openApiSpec from './openapi.json'; |
| 39 | + |
| 40 | +@Module({ |
| 41 | + imports: [ |
| 42 | + OpenAPISerializerModule.forRoot({ |
| 43 | + specSource: { type: 'object', spec: openApiSpec }, |
| 44 | + responseSerialization: { |
| 45 | + enable: true, |
| 46 | + skipErrorResponses: true, |
| 47 | + }, |
| 48 | + }), |
| 49 | + ], |
| 50 | +}) |
| 51 | +export class AppModule {} |
| 52 | +``` |
| 53 | + |
| 54 | +You can disable serialization for specific routes using the `@Serialize` decorator: |
| 55 | + |
| 56 | +```typescript |
| 57 | +import { Serialize } from '@nest-openapi/serializer'; |
| 58 | +import { Body, Controller, Post } from '@nestjs/common'; |
| 59 | + |
| 60 | +@Controller('books') |
| 61 | +export class BooksController { |
| 62 | + @Post() |
| 63 | + @Serialize({ disable: true }) |
| 64 | + create(@Body() dto: CreateBookDto): Book { |
| 65 | + return this.booksService.create(dto); |
| 66 | + } |
| 67 | +} |
| 68 | +``` |
0 commit comments