### Complete Configuration and Controller Example Source: https://tsgonest.dev/docs/openapi/versioning A full setup demonstrating global prefix, URI versioning, and per-route version overrides. ```typescript import { defineConfig } from '@tsgonest/runtime'; export default defineConfig({ nestjs: { globalPrefix: 'api', versioning: { type: 'URI', defaultVersion: '1', prefix: 'v', }, }, openapi: { output: 'dist/openapi.json', title: 'My API', version: '2.0.0', }, }); ``` ```typescript @Controller('users') export class UsersController { /** * @summary List users (v1) */ @Get() findAll(): UserDto[] { ... } // GET /api/v1/users /** * @summary List users (v2) */ @Version('2') @Get() findAllV2(): UserDtoV2[] { ... } // GET /api/v2/users /** * @summary Get user */ @Get(':id') findOne(@Param('id') id: string): UserDto { ... } // GET /api/v1/users/{id} /** * @summary Create user */ @Post() create(@Body() body: CreateUserDto): UserDto { ... } // POST /api/v1/users } ``` -------------------------------- ### tsgonest setup (npm install, tsgonest.config.ts) Source: https://tsgonest.dev/docs/comparisons/vs-nestia-typia Setup for tsgonest: install the package and create a config file. No patches, plugins, or tsconfig modifications are needed. ```bash npm install tsgonest ``` ```typescript import { defineConfig } from '@tsgonest/runtime'; export default defineConfig({ controllers: { include: ['src/**/*.controller.ts'] }, transforms: { validation: true, serialization: true }, openapi: { output: 'dist/openapi.json' }, }); ``` -------------------------------- ### Typia + Nestia setup (npm install, tsconfig.json) Source: https://tsgonest.dev/docs/comparisons/vs-nestia-typia Setup for Typia and Nestia: install packages and run ts-patch, then add plugin entries to tsconfig.json. Requires ts-patch and can conflict with other TypeScript tooling like SWC or esbuild. ```bash npm install typia @nestia/core @nestia/sdk npx ts-patch install ``` ```json { "compilerOptions": { "plugins": [ { "transform": "typia/lib/transform" }, { "transform": "@nestia/core/lib/transform" } ] } } ``` -------------------------------- ### Install @tsgonest/platform-bun Source: https://tsgonest.dev/docs/api/platform-bun Install the package using your preferred package manager. ```bash npm install @tsgonest/platform-bun ``` -------------------------------- ### tsgonest build command examples Source: https://tsgonest.dev/docs/cli Common usage examples for the build command, including custom configurations and debugging options. ```bash # Default build (uses tsconfig.json + auto-detected config) tsgonest build # Custom tsconfig tsgonest build --project tsconfig.build.json # Clean build tsgonest build --clean # Skip type checking for faster builds tsgonest build --no-check # Explicit config path tsgonest build --config configs/tsgonest.config.json -p tsconfig.build.json # Dump type metadata for debugging tsgonest build --dump-metadata ``` -------------------------------- ### Common tsgonest dev usage examples Source: https://tsgonest.dev/docs/cli Various examples demonstrating how to use flags for custom entry points, environment files, debugging, and build configurations. ```bash # Basic watch mode tsgonest dev # With custom entry point tsgonest dev --entry src/main.ts # With environment file tsgonest dev --env-file .env --env-file .env.local # With Node.js debugger tsgonest dev --debug # With custom build config tsgonest dev --project tsconfig.build.json --config tsgonest.config.json # Don't clear terminal on rebuild tsgonest dev --preserveWatchOutput ``` -------------------------------- ### Install @tsgonest/runtime Source: https://tsgonest.dev/docs/api/runtime Command to install the runtime package via npm. ```bash npm install @tsgonest/runtime ``` -------------------------------- ### Complete Example products.controller.ts Source: https://tsgonest.dev/docs/openapi/parameters A comprehensive example demonstrating the use of @Query, @Headers, @Param, and @Body decorators within a NestJS controller to generate OpenAPI documentation. ```typescript @Controller('products') export class ProductsController { /** * Search products with filtering, pagination, and sorting. * @summary Search products */ @Get() findAll( @Query() query: ProductSearchDto, @Headers('accept-language') lang?: string, ): PaginatedResponse { ... } /** * Get a product by ID. * @summary Get product * @throws {404} NotFoundError */ @Get(':id') findOne(@Param('id') id: string): ProductDto { ... } /** * Create a new product. * @summary Create product * @security bearer */ @Post() create(@Body() body: CreateProductDto): ProductDto { ... } /** * Upload a product image. * @summary Upload image * @security bearer * @contentType multipart/form-data */ @Post(':id/image') uploadImage( @Param('id') id: string, @Body() body: ImageUploadDto, ): ImageDto { ... } } ``` -------------------------------- ### Comprehensive OrdersController example Source: https://tsgonest.dev/docs/openapi/controllers Full controller with JSDoc metadata for tags, summaries, security, and error responses. Includes endpoints for list, get, create, cancel, and hidden internal recalculate. Produces six OpenAPI operations under /orders. ```typescript /** * @tag Orders */ @Controller('orders') export class OrdersController { /** * Returns a paginated list of orders for the authenticated user. * * @summary List orders * @security bearer */ @Get() findAll(@Query() query: OrderFilterDto): PaginatedResponse { // ... } /** * Retrieve a single order by ID. * * @summary Get order * @security bearer * @throws {404} NotFoundError */ @Get(':id') findOne(@Param('id') id: string): OrderDto { // ... } /** * Place a new order. * * @summary Create order * @security bearer * @throws {400} ValidationError */ @Post() create(@Body() body: CreateOrderDto): OrderDto { // ... } /** * Cancel an order. Only pending orders can be cancelled. * * @summary Cancel order * @security bearer * @throws {404} NotFoundError * @throws {409} ConflictError */ @Delete(':id') @HttpCode(204) cancel(@Param('id') id: string): void { // ... } /** * @hidden */ @Post('internal/recalculate') recalculate(@Body() body: RecalculateDto): void { // ... } } ``` -------------------------------- ### Install tsgonest with npm Source: https://tsgonest.dev/docs/getting-started Installs the tsgonest CLI and its companion packages. The package includes the CLI binary and automatically installs @tsgonest/runtime and @tsgonest/types as dependencies. ```bash npm install tsgonest ``` -------------------------------- ### Initialize BunAdapter Source: https://tsgonest.dev/docs/api/platform-bun Example of importing and using the BunAdapter in a NestJS application. ```typescript import { BunAdapter } from '@tsgonest/platform-bun'; const app = await NestFactory.create(AppModule, new BunAdapter()); ``` -------------------------------- ### Client setup with createClient Source: https://tsgonest.dev/docs/cli/sdk Initializes the SDK client with a base URL and demonstrates a fully typed request to users.findOne, handling the returned data or error. ```typescript import { createClient } from './sdk'; const api = createClient({ baseUrl: 'http://localhost:3000', }); // Fully typed — params, query, body, and response const { data, error } = await api.users.findOne({ params: { id: '123' } }); if (error) { console.error(error.message); } else { console.log(data.name); // typed as UserDto } ``` -------------------------------- ### Comprehensive DTO example Source: https://tsgonest.dev/docs/validation/jsdoc A complete DTO example demonstrating the use of multiple JSDoc tags for transformation and validation. ```typescript interface CreateProductDto { /** @transform trim @minLength 1 @maxLength 200 */ name: string; /** @transform trim @maxLength 2000 */ description?: string; /** * Product price in USD. * @minimum 0 @multipleOf 0.01 */ price: number; /** * Stock keeping unit. * @transform toUpperCase @pattern ^[A-Z0-9-]+$ */ sku: string; /** * Product tags for search. * @minItems 1 @maxItems 10 @uniqueItems */ tags: string[]; /** * Stock count. * @type uint32 @default 0 */ stock?: number; /** @format url */ imageUrl?: string; /** * Weight in kg. * @exclusiveMinimum 0 @maximum 1000 */ weight?: number; } ``` -------------------------------- ### Install NestJS validation dependencies Source: https://tsgonest.dev/docs/comparisons/vs-nestjs-cli Install the required packages for standard NestJS validation. ```bash npm install class-validator class-transformer ``` -------------------------------- ### Install @nestjs/mapped-types Source: https://tsgonest.dev/docs/migration/post-migration Run this command to install @nestjs/mapped-types if OmitType, PickType, PartialType, or IntersectionType are your only imports from @nestjs/swagger. The migration rewrites the import source to @nestjs/mapped-types. ```bash npm install @nestjs/mapped-types ``` -------------------------------- ### Install NestJS Swagger dependencies Source: https://tsgonest.dev/docs/comparisons/vs-nestjs-cli Install the required packages for the NestJS CLI OpenAPI approach. ```bash npm install @nestjs/swagger swagger-ui-express ``` -------------------------------- ### Run tsgonest migrate with specific options Source: https://tsgonest.dev/docs/cli/migrate Examples for migrating specific files, using custom tsconfig files, or running in CI environments. ```bash # Migrate only DTO files npx tsgonest migrate --apply --include "src/**/*.dto.ts" # Migrate with a custom tsconfig npx tsgonest migrate --apply --tsconfig tsconfig.build.json # CI-friendly: non-interactive, force run npx tsgonest migrate --apply --yes --force ``` -------------------------------- ### tsgonest openapi usage examples Source: https://tsgonest.dev/docs/cli Examples of using the tsgonest openapi command with various flags: default config, --name, --output, --no-check, and --config. These cover common CI/CD and documentation publishing scenarios. ```bash # Generate from default config tsgonest openapi # Generate only the "public" output from a multi-output config tsgonest openapi --name public # Override output path tsgonest openapi --output dist/api-spec.json # Skip type checking for faster generation tsgonest openapi --no-check # Use a specific config tsgonest openapi --config tsgonest.public.config.ts ``` -------------------------------- ### tsgonest build output Source: https://tsgonest.dev/docs/getting-started Example output from running npx tsgonest build. Shows the build steps and timing information. ```text tsgonest v0.3.0 build tsconfig: tsconfig.json config: tsgonest.config.ts emit: 142ms companions: 38ms (4 files) openapi: 12ms total: 192ms ``` -------------------------------- ### Full configuration reference for tsgonest.config.ts Source: https://tsgonest.dev/docs/config An example demonstrating the full configuration structure including OpenAPI metadata and controller exclusion. ```typescript import { defineConfig } from '@tsgonest/runtime'; export default defineConfig({ controllers: { include: ['src/**/*.controller.ts'], exclude: ['src/**/*.spec.ts'], }, transforms: { validation: true, serialization: true, }, openapi: { output: 'dist/openapi.json', title: 'My API', version: '1.0.0', description: 'My NestJS API documentation', }, }); ``` -------------------------------- ### Remove Swagger setup from main.ts (Before) Source: https://tsgonest.dev/docs/openapi/migration The original main.ts with SwaggerModule and DocumentBuilder setup. This code is to be removed during migration. ```typescript import { NestFactory } from '@nestjs/core'; import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); const config = new DocumentBuilder() .setTitle('My API') .setVersion('1.0.0') .addBearerAuth() .build(); const document = SwaggerModule.createDocument(app, config); SwaggerModule.setup('docs', app, document); await app.listen(3000); } bootstrap(); ``` -------------------------------- ### Full tsgonest.config.json example Source: https://tsgonest.dev/docs/openapi/config Complete tsgonest.config.json example showing NestJS global prefix and URI versioning, plus OpenAPI output, title, version, description, contact, license, servers, and security schemes (bearer JWT and OAuth2 authorization code flow). ```json { "nestjs": { "globalPrefix": "api", "versioning": { "type": "URI", "defaultVersion": "1" } }, "openapi": { "output": "dist/openapi.json", "title": "Acme API", "version": "2.1.0", "description": "The Acme Corp public REST API", "contact": { "name": "Acme API Team", "email": "api@acme.com", "url": "https://developer.acme.com" }, "license": { "name": "Apache 2.0", "url": "https://www.apache.org/licenses/LICENSE-2.0" }, "servers": [ { "url": "https://api.acme.com", "description": "Production" }, { "url": "https://sandbox.api.acme.com", "description": "Sandbox" } ], "securitySchemes": { "bearer": { "type": "http", "scheme": "bearer", "bearerFormat": "JWT" }, "oauth2": { "type": "oauth2", "flows": { "authorizationCode": { "authorizationUrl": "https://auth.acme.com/authorize", "tokenUrl": "https://auth.acme.com/token", "scopes": { "read": "Read access", "write": "Write access" } } } } } } } ``` -------------------------------- ### tsgonest dev command syntax Source: https://tsgonest.dev/docs/cli The basic syntax for starting the development server with optional flags and Node.js arguments. ```bash tsgonest dev [flags] [-- node-args...] ``` -------------------------------- ### Install @tsgonest/types with npm Source: https://tsgonest.dev/docs/api/types Install the @tsgonest/types package using npm. The package provides zero-runtime branded types for validation. ```bash npm install @tsgonest/types ``` -------------------------------- ### FormData / file upload example Source: https://tsgonest.dev/docs/cli/sdk Shows how to upload files using the generated buildFormData helper for multipart endpoints. ```typescript await api.uploads.create({ body: buildFormData({ file: myFile, description: 'Photo' }), }); ``` -------------------------------- ### Run tsgonest dev with custom flags Source: https://tsgonest.dev/docs/getting-started Examples of running development mode with custom entry points, environment files, or the Node.js inspector. ```bash # With a custom entry point npx tsgonest dev --entry src/main.ts # With environment files npx tsgonest dev --env-file .env --env-file .env.local # With Node.js inspector for debugging npx tsgonest dev --debug ``` -------------------------------- ### API versioning example Source: https://tsgonest.dev/docs/cli/sdk Shows how to call versioned API endpoints. The SDK groups controllers by version, and globalPrefix and versionPrefix are stripped from paths. ```typescript // Versioned API await api.v1.users.findAll(); await api.v2.users.findAll(); ``` -------------------------------- ### Request body example Source: https://tsgonest.dev/docs/cli/sdk Shows how to send a JSON request body using the body option. ```typescript // POST /users — JSON body await api.users.create({ body: { name: 'Alice', email: 'alice@example.com' }, }); ``` -------------------------------- ### Compare tsgonest type-based approach Source: https://tsgonest.dev/docs/comparisons/vs-nestjs-cli An example of the type-based DTO structure in tsgonest. ```typescript // ✅ tsgonest: types express everything import { Min, Max, Email, Trim, ToLowerCase, Pattern } from '@tsgonest/types'; export interface CreateUserDto { name: string & Trim & Min<1> & Max<255>; email: string & ToLowerCase & Email; age: number & Min<0> & Max<150>; website?: string & Pattern<"^https?:\\/\\/">; } ``` -------------------------------- ### Supported security scheme type examples Source: https://tsgonest.dev/docs/openapi/config Examples of supported security scheme types: http, apiKey, and openIdConnect. The oauth2 type is described as 'See below'. ```json { "type": "http", "scheme": "bearer", "bearerFormat": "JWT" } ``` ```json { "type": "apiKey", "in": "header", "name": "X-API-Key" } ``` ```json { "type": "openIdConnect", "openIdConnectUrl": "https://..." } ``` -------------------------------- ### Abort signal example Source: https://tsgonest.dev/docs/cli/sdk Shows how to cancel a request using an AbortController and passing its signal to the SDK method. ```typescript const controller = new AbortController(); await api.users.findAll({ query: { page: 1 }, signal: controller.signal, }); // Cancel the request controller.abort(); ``` -------------------------------- ### Run tsgonest in development mode Source: https://tsgonest.dev/docs/getting-started Use this command to start watch-mode development with automatic rebuilds and restarts. ```bash npx tsgonest dev ``` -------------------------------- ### Compare NestJS CLI decorator approach Source: https://tsgonest.dev/docs/comparisons/vs-nestjs-cli An example of the decorator-based DTO structure in NestJS. ```typescript // ❌ NestJS CLI: decorator soup, type duplication export class CreateUserDto { @IsString() @MinLength(1) @MaxLength(255) @Transform(({ value }) => value?.trim()) name: string; @IsEmail() @Transform(({ value }) => value?.toLowerCase()) email: string; @IsNumber() @Min(0) @Max(150) age: number; @IsOptional() @IsString() @Matches(/^https?:\/\//) website?: string; } ``` -------------------------------- ### Before Migration (Nestia + Typia) Source: https://tsgonest.dev/docs/migration/nestia-typia Example of a NestJS controller using Nestia's @TypedRoute, @TypedQuery, and @TypedBody decorators alongside Typia tags. ```typescript import { TypedRoute, TypedBody, TypedQuery } from '@nestia/core'; import { Controller } from '@nestjs/common'; import { tags } from 'typia'; interface SearchQuery { q: string & tags.MinLength<1>; page: number & tags.Minimum<1>; } interface CreateUserInput { email: string & tags.Format<'email'>; name: string & tags.MinLength<1>; } @Controller('users') export class UsersController { @TypedRoute.Get() findAll(@TypedQuery() query: SearchQuery) { return this.usersService.findAll(query); } @TypedRoute.Post() create(@TypedBody() body: CreateUserInput) { return this.usersService.create(body); } } ``` -------------------------------- ### SSE connection example Source: https://tsgonest.dev/docs/cli/sdk Shows how to consume Server-Sent Events (SSE) using the typed SSEConnection. The event and data are typed based on the event name. ```typescript const { data: response } = await api.orders.events({ params: { id: '123' } }); const sse = new SSEConnection(response); for await (const event of sse) { // event.event is typed ('created' | 'shipped' | 'cancelled') // event.data is typed per event name console.log(event.event, event.data); } ``` -------------------------------- ### Clean main.ts with zero runtime setup (src/main.ts) Source: https://tsgonest.dev/docs/serialization-runtime Standard NestJS bootstrap without any tsgonest-specific configuration. The integration is entirely compile-time. ```typescript import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); await app.listen(3000); } bootstrap(); ``` -------------------------------- ### Migrate UsersController to JSDoc Source: https://tsgonest.dev/docs/openapi/migration This example shows the transition of a NestJS controller from using @nestjs/swagger decorators to JSDoc comments for OpenAPI documentation. ```typescript import { Controller, Get, Post, Put, Delete, Body, Param, Query } from '@nestjs/common'; import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth, ApiQuery } from '@nestjs/swagger'; @ApiTags('Users') @ApiBearerAuth() @Controller('users') export class UsersController { @ApiOperation({ summary: 'List users', description: 'Returns a paginated list of users.' }) @ApiQuery({ name: 'page', type: Number, required: false }) @ApiQuery({ name: 'limit', type: Number, required: false }) @ApiResponse({ status: 200, type: [UserDto] }) @Get() findAll( @Query('page') page?: number, @Query('limit') limit?: number, ): UserDto[] { // ... } @ApiOperation({ summary: 'Get user' }) @ApiResponse({ status: 200, type: UserDto }) @ApiResponse({ status: 404, description: 'User not found' }) @Get(':id') findOne(@Param('id') id: string): UserDto { // ... } @ApiOperation({ summary: 'Create user' }) @ApiResponse({ status: 201, type: UserDto }) @ApiResponse({ status: 400, description: 'Validation failed' }) @Post() create(@Body() body: CreateUserDto): UserDto { // ... } @ApiOperation({ summary: 'Update user' }) @ApiResponse({ status: 200, type: UserDto }) @ApiResponse({ status: 404, description: 'User not found' }) @Put(':id') update(@Param('id') id: string, @Body() body: UpdateUserDto): UserDto { // ... } @ApiOperation({ summary: 'Delete user' }) @ApiResponse({ status: 204 }) @ApiResponse({ status: 404, description: 'User not found' }) @Delete(':id') remove(@Param('id') id: string): void { // ... } } ``` ```typescript import { Controller, Get, Post, Put, Delete, Body, Param, Query, HttpCode } from '@nestjs/common'; /** * @security bearer */ @Controller('users') export class UsersController { /** * Returns a paginated list of users. * @summary List users */ @Get() findAll( @Query('page') page?: number, @Query('limit') limit?: number, ): UserDto[] { // ... } /** * @summary Get user * @throws {404} NotFoundError */ @Get(':id') findOne(@Param('id') id: string): UserDto { // ... } /** * @summary Create user * @throws {400} ValidationError */ @Post() create(@Body() body: CreateUserDto): UserDto { // ... } /** * @summary Update user * @throws {404} NotFoundError */ @Put(':id') update(@Param('id') id: string, @Body() body: UpdateUserDto): UserDto { // ... } /** * @summary Delete user * @throws {404} NotFoundError */ @Delete(':id') @HttpCode(204) remove(@Param('id') id: string): void { // ... } } ``` -------------------------------- ### @Sse decorator example Source: https://tsgonest.dev/docs/openapi/controllers Legacy NestJS @Sse decorator maps to a GET operation with text/event-stream content type. Example shows @Sse('stream') on a controller method returning Observable. ```typescript @Controller('notifications') export class NotificationsController { @Sse('stream') stream(): Observable { ... } // GET /notifications/stream // Response: text/event-stream with itemSchema } ``` -------------------------------- ### StartsWith prefix validation Source: https://tsgonest.dev/docs/validation/string-tags The string must start with the given prefix. Example shows secure URL and API path constraints. ```TypeScript import { StartsWith } from '@tsgonest/types'; interface UrlDto { secureUrl: string & StartsWith<"https://">; apiPath: string & StartsWith<"/api/">; } ``` -------------------------------- ### @EventStream decorator example Source: https://tsgonest.dev/docs/openapi/controllers Type-safe SSE with discriminated event unions, compile-time validation/serialization, and automatic OpenAPI schemas. Uses @EventStream('events', { heartbeat: 30_000 }) to expose GET /orders/events with text/event-stream response. ```typescript import { EventStream, SseEvent, SseEvents } from '@tsgonest/runtime'; type OrderEvents = SseEvents<{ created: OrderDto; shipped: OrderDto; cancelled: { id: string; reason: string }; }>; @Controller('orders') export class OrdersController { @EventStream('events', { heartbeat: 30_000 }) async *events(): AsyncGenerator { ... } // GET /orders/events // Response: text/event-stream with discriminated oneOf itemSchema } ``` -------------------------------- ### Install dependencies with npm, pnpm, or yarn Source: https://tsgonest.dev/docs/migration/post-migration Sync your lockfile after the migration adds tsgonest, @tsgonest/runtime, and @tsgonest/types to package.json and removes old packages. Choose the command for your package manager. ```bash npm install ``` ```bash pnpm install ``` ```bash yarn install ``` -------------------------------- ### Path, query, and header parameters Source: https://tsgonest.dev/docs/cli/sdk Demonstrates how to pass path, query, and header parameters to SDK methods. Parameters are fully typed based on controller signatures. ```typescript // GET /users/:id — path params await api.users.findOne({ params: { id: '123' } }); // GET /users?page=1&limit=10 — query params await api.users.findAll({ query: { page: 1, limit: 10 } }); // Custom headers await api.users.findAll({ headers: { 'x-api-key': 'abc' } }); ``` -------------------------------- ### Run development mode with Bun runtime Source: https://tsgonest.dev/docs/api/platform-bun Use the tsgonest CLI to run the development server with the Bun runtime. ```bash tsgonest dev --runtime bun ``` -------------------------------- ### TsgonestValidationError example response Source: https://tsgonest.dev/docs/api/runtime Example JSON response structure when a TsgonestValidationError is caught by NestJS. ```json { "statusCode": 400, "message": "Validation failed", "errors": [ { "property": "input.email", "constraints": { "tsgonest": "expected string (email), received string" } } ] } ``` -------------------------------- ### Run application with Bun Source: https://tsgonest.dev/docs/api/platform-bun Execute the compiled main.js file using the Bun runtime. ```bash bun dist/main.js ``` -------------------------------- ### CreateAccountDto validation example Source: https://tsgonest.dev/docs/validation/string-tags A practical example of using @tsgonest/types validation tags within a DTO interface definition. ```typescript import { Email, Trim, ToLowerCase, MinLength, MaxLength, Pattern, Url, Uuid, Between, } from '@tsgonest/types'; interface CreateAccountDto { email: string & Trim & ToLowerCase & Email; password: string & Between<{ min: 8; max: 128 }>; displayName: string & Trim & MinLength<{ value: 1; error: "Display name is required" }> & MaxLength<50>; slug: string & Trim & ToLowerCase & MinLength<3> & MaxLength<40> & Pattern<{ value: "^[a-z0-9]+(?:-[a-z0-9]+)*$"; error: "Slug may only contain lowercase letters, numbers, and hyphens" }>; avatarUrl?: string & Url; referralCode?: string & Uuid; } ``` -------------------------------- ### Run the test suite with npm test Source: https://tsgonest.dev/docs/migration/post-migration Executes the project's test suite to verify the migration. Run this after completing all migration steps. ```bash npm test ``` -------------------------------- ### Apply migration changes interactively Source: https://tsgonest.dev/docs/migration Execute the migration with the --apply flag to be prompted for each step, including dependency removal and configuration generation. ```bash npx tsgonest migrate --apply ``` -------------------------------- ### @maxLength tag example Source: https://tsgonest.dev/docs/validation/jsdoc Example DTO using the @maxLength tag to enforce a maximum string length of 280. ```typescript interface PostDto { /** @maxLength 280 */ content: string; } ``` -------------------------------- ### @minLength tag example Source: https://tsgonest.dev/docs/validation/jsdoc Example DTO using the @minLength tag to enforce a minimum string length of 1. ```typescript interface SignupDto { /** @minLength 1 */ username: string; } ``` -------------------------------- ### tsgonest build and sdk commands Source: https://tsgonest.dev/docs/cli/sdk Shows the two main CLI commands: 'tsgonest build' compiles and generates openapi.json plus the SDK, while 'tsgonest sdk' regenerates the SDK from an existing openapi.json. ```bash tsgonest build # Compiles + generates openapi.json + SDK ``` ```bash tsgonest sdk # Regenerate SDK from existing openapi.json ``` -------------------------------- ### tsgonest check examples Source: https://tsgonest.dev/docs/cli Examples of tsgonest check usage: one-shot check, watch mode, custom tsconfig, and skipping type checking. ```bash # One-shot check tsgonest check # Continuous watch tsgonest check --watch # Custom tsconfig tsgonest check --project tsconfig.build.json # Skip type checking for tsgonest-only analysis tsgonest check --no-check ``` -------------------------------- ### Preview migration changes Source: https://tsgonest.dev/docs/migration Run a dry-run to scan the project and display a diff of proposed changes without modifying any files. ```bash npx tsgonest migrate ``` -------------------------------- ### Bootstrap NestJS with BunAdapter Source: https://tsgonest.dev/docs/api/platform-bun Initialize a NestJS application using the BunAdapter as the HTTP adapter. ```typescript import { NestFactory } from '@nestjs/core'; import { BunAdapter } from '@tsgonest/platform-bun'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule, new BunAdapter()); await app.listen(3000); } bootstrap(); ``` -------------------------------- ### Uppercase constraint example (uppercase.dto.ts) Source: https://tsgonest.dev/docs/validation/string-tags Uppercase requires the string to be entirely uppercase. The example shows a custom error message option. 'US' passes, 'us' fails. ```typescript import { Uppercase } from '@tsgonest/types'; interface CountryDto { // "US" passes, "us" fails code: string & Uppercase; // With custom error state: string & Uppercase<{ error: "State code must be uppercase" }>; } ``` -------------------------------- ### Run tsgonest build Source: https://tsgonest.dev/docs/comparisons/vs-tsgo Command to execute the tsgonest build process. ```bash tsgonest build ``` -------------------------------- ### @pattern tag example Source: https://tsgonest.dev/docs/validation/jsdoc Example DTO using the @pattern tag to validate against a regular expression. The regex is tested using JavaScript's RegExp; avoid lookbehind assertions for broad engine compatibility. ```typescript interface SlugDto { /** @pattern ^[a-z0-9-]+$ */ slug: string; } ``` -------------------------------- ### Remove SwaggerModule setup from main.ts Source: https://tsgonest.dev/docs/migration/post-migration Delete this code from main.ts if you had Swagger UI setup. tsgonest generates OpenAPI at build time; serve the generated JSON file statically or use Swagger UI pointed at the output file. ```typescript // Remove all of this from main.ts: const config = new DocumentBuilder() .setTitle('My API') .addBearerAuth() .build(); const document = SwaggerModule.createDocument(app, config); SwaggerModule.setup('api', app, document); ``` -------------------------------- ### tsgonest build command syntax Source: https://tsgonest.dev/docs/cli The basic syntax for the build command. ```bash tsgonest build [flags] ``` -------------------------------- ### Complete NestJS Controller with OpenAPI Decorators Source: https://tsgonest.dev/docs/openapi/returns Complete NestJS controller example showing OpenAPI generation with @summary, @security, @throws, @Returns, and @Sse decorators. Demonstrates CRUD endpoints, file download with @Res(), and SSE updates. ```typescript @Controller('documents') export class DocumentsController { /** * List all documents for the current user. * @summary List documents * @security bearer */ @Get() findAll(@Query() query: DocumentFilterDto): DocumentDto[] { ... } /** * Get document metadata. * @summary Get document * @security bearer * @throws {404} NotFoundError */ @Get(':id') findOne(@Param('id') id: string): DocumentDto { ... } /** * Download the document file. * @summary Download document * @security bearer * @throws {404} NotFoundError */ @Get(':id/download') @Returns({ contentType: 'application/pdf', description: 'The document file' }) download(@Param('id') id: string, @Res() res: Response): void { const doc = this.service.getDocument(id); res.set('Content-Type', doc.mimeType).send(doc.buffer); } /** * Create a new document. * @summary Create document * @security bearer * @throws {400} ValidationError */ @Post() create(@Body() body: CreateDocumentDto): DocumentDto { ... } /** * Subscribe to real-time document updates. * @summary Document update stream * @security bearer */ @Sse(':id/updates') updates(@Param('id') id: string): Observable { ... } /** * Delete a document permanently. * @summary Delete document * @security bearer * @throws {404} NotFoundError */ @Delete(':id') @HttpCode(204) remove(@Param('id') id: string): void { ... } } ``` -------------------------------- ### Generate SDK with tsgonest sdk Source: https://tsgonest.dev/docs/cli/sdk Run `tsgonest sdk` to generate SDKs for all outputs with `sdk.output` configured, or use `--name` to target a specific output and `--output` to override the directory. ```bash # Generate SDK for all outputs that have sdk.output configured tsgonest sdk # Generate SDK for a specific named output tsgonest sdk --name public # Override output directory tsgonest sdk --name public --output ./client ``` -------------------------------- ### Create tsgonest.config.ts with defineConfig() Source: https://tsgonest.dev/docs/getting-started Creates tsgonest.config.ts in the project root. The defineConfig() helper provides full autocomplete and type checking. tsgonest auto-detects this file in the working directory. ```typescript import { defineConfig } from '@tsgonest/runtime'; export default defineConfig({ controllers: { include: ['src/**/*.controller.ts'], }, transforms: { validation: true, serialization: true, }, openapi: { output: 'dist/openapi.json', }, }); ``` -------------------------------- ### Practical example: Order items Source: https://tsgonest.dev/docs/validation/array-tags Validate an array of objects where each object has its own internal validation constraints. ```typescript import { MinItems, MaxItems, Min, Int } from '@tsgonest/types'; interface OrderItemDto { productId: string; quantity: number & Int & Min<1>; } interface CreateOrderDto { items: OrderItemDto[] & MinItems<{ value: 1; error: "Order must contain at least one item" }> & MaxItems<100>; note?: string; } ``` -------------------------------- ### Run tsgonest migrate commands Source: https://tsgonest.dev/docs/cli/migrate Commands to preview changes, apply them interactively, or apply them non-interactively using default settings. ```bash # Preview changes (dry-run, no files modified) npx tsgonest migrate # Apply changes (interactive) npx tsgonest migrate --apply # Apply changes (non-interactive, accept all defaults) npx tsgonest migrate --apply --yes ``` -------------------------------- ### Practical example: Tags Source: https://tsgonest.dev/docs/validation/array-tags Validate an array of strings with length constraints on both the array and the individual items. ```typescript import { MinItems, MaxItems, UniqueItems, MinLength, MaxLength, Trim } from '@tsgonest/types'; interface ArticleDto { title: string & Trim & MinLength<1> & MaxLength<200>; // Tags: 1-10 unique strings, each 1-30 chars tags: (string & Trim & MinLength<1> & MaxLength<30>)[] & MinItems<1> & MaxItems<10> & UniqueItems; } ``` -------------------------------- ### Define array constraints in DTO Source: https://tsgonest.dev/docs/validation/array-tags Example of applying MinItems, MaxItems, and UniqueItems to an array property. ```typescript import { MinItems, MaxItems, UniqueItems } from '@tsgonest/types'; interface CreatePostDto { tags: string[] & MinItems<1> & MaxItems<10> & UniqueItems; } ``` -------------------------------- ### Before class-validator DTO conversion Source: https://tsgonest.dev/docs/migration/class-validator An example of a standard DTO class using class-validator decorators before migration. ```typescript import { IsEmail, IsNotEmpty, MinLength, IsOptional } from 'class-validator'; export class CreateUserDto { @IsEmail() @IsNotEmpty() email: string; @MinLength(6) password: string; @IsOptional() @IsNotEmpty() nickname?: string; } ``` -------------------------------- ### Define DTO with String Constraints Source: https://tsgonest.dev/docs/validation/string-tags Example of using Email, MinLength, and MaxLength branded types in a DTO. ```typescript import { Email, MinLength, MaxLength } from '@tsgonest/types'; interface CreateUserDto { email: string & Email; username: string & MinLength<3> & MaxLength<20>; } ``` -------------------------------- ### Companion file structure Source: https://tsgonest.dev/docs/validation Shows the output structure of tsgonest build, which emits one companion file per exported type. ```text dist/ user.dto.js ← tsgo output user.dto.CreateUserDto.tsgonest.js ← generated validator + serializer user.dto.CreateUserDto.tsgonest.d.ts ← generated type declarations ``` -------------------------------- ### Configure contact and license in tsgonest.config.json Source: https://tsgonest.dev/docs/openapi/config Add contact and license details to the OpenAPI info block in tsgonest.config.json. ```json { "openapi": { "output": "dist/openapi.json", "title": "My API", "version": "1.0.0", "contact": { "name": "API Support", "url": "https://example.com/support", "email": "support@example.com" }, "license": { "name": "MIT", "url": "https://opensource.org/licenses/MIT" } } } ``` -------------------------------- ### Validate DTO with tsgonest Source: https://tsgonest.dev/docs/comparisons/vs-nestia-typia Validation is injected at compile time, requiring no explicit calls or runtime setup. ```typescript // tsgonest — automatic, no explicit calls needed @Controller('users') export class UserController { @Post() create(@Body() dto: CreateUserDto) { return this.userService.create(dto); } } ```