Skip to content

The typeix/resty-swagger package: an OpenAPI 3.1 document generated from the live routes, plus a documentation UI.

typeix/resty-swagger

7 min read Source

OpenAPI 3.1 document generation and Swagger UI for the resty framework.

The document is generated from the routes pipeServer actually registered, so it cannot drift from the router, and document generation never mutates decorator metadata used by dependency injection.

Requirements

  • Node.js ^26.0.0
  • @typeix/resty ^9.2.0

Install

npm i @typeix/resty-swagger

Quick start

import {createServer} from "http";
import {pipeServer, Controller, GET, POST, Inject, PathParam, RootModule} from "@typeix/resty";
import {pipeSwagger, ApiProperty, ApiResponse, ApiTags, ApiOperation} from "@typeix/resty-swagger";

class UserDto {
  @ApiProperty({example: "u-1"})
  id: string;

  @ApiProperty()
  name: string;
}

@ApiTags("users")
@Controller({path: "/users"})
class UsersController {
  @GET("/<id:(\\d+)>")
  @ApiOperation({summary: "Get a user"})
  @ApiResponse({status: 200, type: UserDto})
  @ApiResponse({status: 404, description: "Not found"})
  findById(@PathParam("id") id: number): UserDto {
    return null;
  }
}

@RootModule({shared_providers: [], controllers: [UsersController]})
class Application {
}

async function bootstrap() {
  const server = createServer();
  await pipeServer(server, Application);
  await pipeSwagger(server, Application, {
    path: "/docs",
    info: {title: "Users API", version: "1.0.0"}
  });
  server.listen(8080);
}

pipeSwagger must be called after pipeServer, it reads the module injector that pipeServer stored on the root module class, exactly like pipeWebSocket does.

Route Content
GET /docs documentation page
GET /docs/openapi.json OpenAPI document
GET /docs/openapi.yaml same document as YAML, with yaml: true

Decorators

All decorators are metadata only, they never change runtime behavior.

Operations

Decorator Level Purpose
@ApiTags("users") class group operations, defaults to the controller name
@ApiOperation({summary, description, operationId, deprecated, tags}) method operation documentation
@ApiExcludeEndpoint() method hide a route
@ApiExcludeController() class hide all routes of a controller

Parameters

Decorator Purpose
@ApiParam({name, type, description, example, pattern}) or @ApiParam("id") path parameter
@ApiQuery({name, required, type, enum, example}) or @ApiQuery("page") query parameter
@ApiHeader({name, required, type}) header parameter
@ApiBody({type, required, description, example}) request body

Path parameters are always documented, the name is taken from the route template. Query and header parameters must be declared, parameter names are erased at runtime.

Responses

Decorator Purpose
@ApiResponse({status, description, type, isArray, schema, example}) repeatable per status code
@ApiProduces("application/xml") content type override

A response without type and with a 4xx/5xx status references the shared ErrorResponse schema, which mirrors the payload Router#requestHandler produces on failure.

@Produces(...) from resty is also honoured for the content type.

Security

Decorator Purpose
@ApiBearerAuth() bearer requirement, the http bearer scheme is registered automatically
@ApiSecurity("oauth2", ["read"]) custom requirement, the scheme must be described in securitySchemes

Models

enum Role {
  Admin,
  User
}

@ApiSchema({name: "User"})
class UserDto {
  @ApiProperty({example: "u-1", description: "Stable id"})
  id: string;

  @ApiProperty({required: false})
  nickname: string;

  @ApiProperty({enum: Role, enumName: "Role"})
  role: Role;

  @ApiProperty({type: () => [PostDto]})
  posts: PostDto[];

  @ApiHideProperty()
  password: string;
}

type: () => Dto is lazy and used to break circular imports. It is required for interfaces, unions, generics and arrays of models, because TypeScript erases those types at runtime.

Every unknown option (minLength, format, additionalProperties, ...) is copied into the property schema.

Options

pipeSwagger accepts document options and ui options in one object:

Option Default Description
info {title: "API", version: "1.0.0"} document info
servers – server list
specVersion "3.1.0" "3.0.3" for older code generators
tags, security, securitySchemes – document level fields
include, exclude – controller lists
includePathPrefix – only document routes under these path prefixes
stripPathPrefix – remove a prefix from documented paths
operationIdFactory controller.method operation id generator
strict false throw when diagnostics were produced
path "/docs" mount path
ui "swagger" "swagger", "scalar", "redoc", "none"
cdn true load the ui from a CDN, false needs swagger-ui-dist
assets resolved swagger-ui-dist directory with self hosted assets
yaml false serve /openapi.yaml
title document title page title

Programmatic usage

import {SwaggerModule} from "@typeix/resty-swagger";

// build time, walks the module graph without booting the server
const document = SwaggerModule.createDocument(Application, {info: {title: "Users API", version: "1.0.0"}});
await SwaggerModule.writeDocument(document, "openapi.json");

// from a booted application
const document = SwaggerModule.createDocumentFromInjector(moduleInjector);

// custom mounting
SwaggerModule.setup("/api-docs", injector, document, {ui: "scalar"});

A build time export can run in CI to keep a published spec under version control:

{
  "scripts": {
    "openapi": "ts-node -e \"import {SwaggerModule} from '@typeix/resty-swagger'; SwaggerModule.writeDocument(SwaggerModule.createDocument(require('./src/app.module').Application), 'openapi.json')\""
  }
}

Multiple API versions

One HTTP server serves exactly one root module. Calling pipeServer twice on the same server does not work: each call pipes its own Router, both listen to request, and the router that does not match answers 404 and ends the response, so every request fails. Put all versions inside one module graph and use module path as the version.

One application, one document

@Module({path: "/v1", controllers: [UsersV1Controller]})
class V1Module {
}

@Module({path: "/v2", controllers: [UsersV2Controller]})
class V2Module {
}

@RootModule({shared_providers: [], controllers: [], imports: [V1Module, V2Module]})
class Application {
}

await pipeServer(server, Application);
await pipeSwagger(server, Application, {path: "/docs"});

Routes are served as /v1/users and /v2/users, the document contains both, and Swagger UI can call both directly. A module path prefixes only its own controllers, ancestor module paths do not accumulate.

Mark the old version as deprecated per operation with @ApiOperation({deprecated: true}), or hide it from the combined document with exclude: [UsersV1Controller].

One document per version

pipeSwagger can be called once per mount path, each call builds its own document:

await pipeSwagger(server, Application, {
  path: "/docs/v1",
  include: [UsersV1Controller],
  info: {title: "Users API", version: "1.0.0"}
});
await pipeSwagger(server, Application, {
  path: "/docs/v2",
  include: [UsersV2Controller],
  info: {title: "Users API", version: "2.0.0"}
});

include filters by controller class. When the same controller is mounted under two versions, split by path instead, includePathPrefix matches whole segments so /v1 does not match /v10:

await pipeSwagger(server, Application, {
  path: "/docs/v1",
  includePathPrefix: "/v1",
  info: {title: "Items API", version: "1.0.0"}
});

Version in the server instead of the path

To document /users instead of /v2/users, strip the prefix and move it into servers, which is how most public API references are laid out:

await pipeSwagger(server, Application, {
  path: "/docs/v2",
  includePathPrefix: "/v2",
  stripPathPrefix: "/v2",
  servers: [{url: "/v2"}],
  info: {title: "Users API", version: "2.0.0"}
});

A stripPathPrefix that matches nothing is reported as a diagnostic, so a typo does not silently produce a document with wrong paths.

Diagnostics

A route that cannot be represented is reported, never emitted half broken:

[resty-swagger] warn: UsersController.create: route "*" skipped, wildcard segment is not expressible as an OpenAPI path
[resty-swagger] warn: UserDto.meta: reflected type is not resolvable, annotate it with @ApiProperty({type})
[resty-swagger] warn: duplicate route GET /dup, keeping the first definition

Diagnostics are attached to the document under a symbol and read with getDiagnostics(document), so they are never serialized into the spec. strict: true turns them into an exception, which works well as a CI gate.

Limitations

  • Interfaces, type aliases, unions and generics are erased. Annotate them explicitly, design:type is Object at runtime. This includes import type imports.
  • Async return types are erased to Promise. Use @ApiResponse({type: UserDto}) for Promise<UserDto>.
  • No query parameter inference. Parameter names are not available at runtime, declare them with @ApiQuery.
  • No parameter level swagger decorators. Resty resolves handler arguments from the injector and reads parameter tokens, a parameter decorator would change dependency injection at runtime.
  • Regular expression and wildcard routes are skipped with a diagnostic, they cannot be expressed as an OpenAPI path.