exisjs/swagger
The exisjs/swagger module provides automated OpenAPI 3.1 specification generation, interactive UI rendering (Swagger UI and Scalar), schema introspection from TexEngine validators, and OpenAPI operation decorators.
Module Exports
import { swagger, docs, defineSwagger, defineDocs, generateOpenApiSpec, renderDocumentationHtml, mountDocumentation, normalizeOpenApiPath, schemaToOpenApi, ApiTags, Tags, ApiOperation, Operation, ApiResponse, ApiBearerAuth, BearerAuth, ApiSecurity, ApiExclude, ApiProperty,} from 'exisjs/swagger'
import type { SwaggerConfig, OpenApiSpec, OpenApiInfo, OpenApiServer, OpenApiTag, OpenApiOperation, OpenApiParameter, OpenApiRequestBody, OpenApiResponse, SecuritySchemeObject, RouteDocMetadata,} from 'exisjs/swagger'1. Configuration Interface (SwaggerConfig)
Configuration options passed to swagger(config) or configured under exis.config.ts:
| Option | Type | Default | Description |
|---|---|---|---|
enabled | boolean | false | Enables or disables OpenAPI specification generation and documentation endpoints. |
path | string | '/docs' | Base URL path where the interactive documentation UI is mounted. |
specPath | string | '/docs/json' | URL path where the raw OpenAPI 3.1.0 JSON specification is served. |
title | string | 'ExisJS API Documentation' | API Title displayed in documentation headers and page metadata. |
version | string | '1.0.0' | Semantic version string of the API. |
description | string | undefined | High-level API summary or Markdown description rendered in the UI header. |
termsOfService | string | undefined | URL pointing to the API Terms of Service. |
contact | OpenApiInfo['contact'] | undefined | Contact metadata (name, url, email). |
license | OpenApiInfo['license'] | undefined | License descriptor (name, url). |
ui | 'swagger-ui' | 'scalar' | 'swagger-ui' | Interactive documentation UI renderer. |
servers | OpenApiServer[] | [{ url: '/' }] | Array of server environment definitions (url, description, variables). |
tags | OpenApiTag[] | [] | Global tag descriptors for grouping endpoints (name, description, externalDocs). |
security | Record<string, string[]>[] | [] | Global security requirements applied to all operations unless overridden. |
securitySchemes | Record<string, SecuritySchemeObject> | {} | Reusable authentication schemes (apiKey, http Bearer, oauth2, openIdConnect). |
customCss | string | undefined | Custom CSS stylesheet injected into the documentation HTML. |
customFavicon | string | undefined | Custom favicon image URL. |
transformSpec | (spec: OpenApiSpec) => OpenApiSpec | void | undefined | Hook to mutate or extend the generated specification before serving. |
2. Mounting Documentation
swagger(config?) / docs(config?)
Mounts documentation routes onto an ExisJS App instance during startup:
function swagger(config?: SwaggerConfig): (app: App) => voidExample
import { exis } from 'exisjs'import { swagger } from 'exisjs/swagger'
export default exis({ onStart(app) { swagger({ title: 'E-Commerce Platform API', version: '2.4.0', path: '/docs', specPath: '/docs/openapi.json', ui: 'scalar', securitySchemes: { bearerAuth: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT', }, }, })(app) },})3. OpenAPI Decorators (exisjs/swagger)
Decorators attach metadata to class controllers and method handlers for OpenAPI specification generation.
@ApiTags(...tags: string[]) / @Tags(...)
Assigns one or more operational tags to a controller class or individual route method.
function ApiTags(...tags: string[]): ClassDecorator & MethodDecoratorimport { Controller, Get } from 'exisjs/decorators'import { ApiTags } from 'exisjs/swagger'
@ApiTags('Users', 'Administration')@Controller('/users')export default class UsersController { @Get('/') listUsers() { return [] }}@ApiOperation(options) / @Operation(...)
Attaches summary, detailed description, operation ID, and deprecation flags to an endpoint.
function ApiOperation(options: { summary?: string description?: string operationId?: string deprecated?: boolean externalDocs?: { url: string; description?: string }}): MethodDecoratorimport { Controller, Get, Param } from 'exisjs/decorators'import { ApiOperation } from 'exisjs/swagger'
@Controller('/users')export default class UsersController { @Get('/:id') @ApiOperation({ summary: 'Retrieve User by ID', description: 'Fetches complete user profile metadata from the database.', operationId: 'getUserById', deprecated: false, }) getUser(@Param('id') id: string) { return { id, name: 'Alice' } }}@ApiResponse(options)
Documents expected response HTTP status codes, descriptions, and response body schemas.
function ApiResponse(options: { status: number | string description?: string schema?: any}): MethodDecoratorimport { Controller, Get, Param } from 'exisjs/decorators'import { ApiResponse } from 'exisjs/swagger'import { tex } from 'exisjs/validator'
const UserResponseSchema = tex.object({ id: tex.uuid(), name: tex.string(), email: tex.email(),})
@Controller('/users')export default class UsersController { @Get('/:id') @ApiResponse({ status: 200, description: 'User successfully retrieved.', schema: UserResponseSchema, }) @ApiResponse({ status: 404, description: 'User not found for given ID.', }) getUser(@Param('id') id: string) { return { id, name: 'Alice', email: '[email protected]' } }}@ApiBearerAuth(name?) / @BearerAuth(...)
Enforces Bearer JWT authentication requirement on an entire controller or specific endpoint in OpenAPI.
function ApiBearerAuth(name = 'bearerAuth'): ClassDecorator & MethodDecoratorimport { Controller, Get } from 'exisjs/decorators'import { ApiBearerAuth } from 'exisjs/swagger'
@ApiBearerAuth()@Controller('/account')export default class AccountController { @Get('/profile') getProfile() { return { status: 'authenticated' } }}@ApiSecurity(name, scopes?)
Enforces custom security requirements on an endpoint or controller.
function ApiSecurity(name: string, scopes?: string[]): ClassDecorator & MethodDecoratorimport { Controller, Get } from 'exisjs/decorators'import { ApiSecurity } from 'exisjs/swagger'
@Controller('/admin')export default class AdminController { @Get('/metrics') @ApiSecurity('apiKeyAuth', ['read:admin']) getMetrics() { return { memory: process.memoryUsage() } }}@ApiExclude()
Excludes an endpoint or entire controller class from OpenAPI generation and documentation UIs.
function ApiExclude(): ClassDecorator & MethodDecoratorimport { Controller, Get } from 'exisjs/decorators'import { ApiExclude } from 'exisjs/swagger'
@Controller('/internal')export default class InternalController { @Get('/healthcheck') @ApiExclude() healthCheck() { return { ok: true } }}@ApiProperty(options?)
Annotates class properties with metadata for OpenAPI schema extraction.
function ApiProperty(options?: { description?: string example?: any required?: boolean type?: any enum?: any[]}): PropertyDecoratorimport { ApiProperty } from 'exisjs/swagger'
export class CreateUserDto { @ApiProperty({ description: 'Unique email address of the account owner', example: '[email protected]', required: true, }) email!: string
@ApiProperty({ description: 'Account display name', example: 'Jane Doe', required: false, }) name?: string}4. Programmatic Generation Utilities
generateOpenApiSpec(routesOrApp, config?)
Pure generator function that scans routes, URL parameters, TexEngine validation schemas, and reflection metadata, producing a compliant OpenAPI 3.1.0 specification object.
function generateOpenApiSpec( routesOrApp: Route[] | App, config?: SwaggerConfig): OpenApiSpecExample
import { generateOpenApiSpec } from 'exisjs/swagger'import { getActiveApp } from 'exisjs'
const app = getActiveApp()const spec = generateOpenApiSpec(app, { title: 'Exported OpenAPI Spec', version: '1.0.0',})renderDocumentationHtml(config)
Generates standalone HTML markup embedding Swagger UI or Scalar API client scripts.
function renderDocumentationHtml(config: SwaggerConfig): stringParameters
| Property | Type | Description |
|---|---|---|
config.ui | 'swagger-ui' | 'scalar' | The chosen UI documentation theme. |
config.specPath | string | Target URL path where the UI fetches the OpenAPI JSON specification. |
config.title | string | Document <title> tag content. |
config.customCss | string | Injected stylesheet string. |
config.customFavicon | string | Injected favicon link. |
schemaToOpenApi(validator)
Converts any schema descriptor (TexEngine, TexType, TexDiscriminatedUnionEngine, Zod object/primitive, or raw property descriptor map) into an OpenAPI 3.1 compatible JSON Schema definition.
function schemaToOpenApi(validator: any): Record<string, any>Example
import { schemaToOpenApi } from 'exisjs/swagger'import { tex } from 'exisjs/validator'import { z } from 'zod'
// Translates native TexEngineconst texJsonSchema = schemaToOpenApi( tex.object({ id: tex.uuid(), count: tex.number({ min: 1 }) }))
// Translates Zod schemas via duck typingconst zodJsonSchema = schemaToOpenApi( z.object({ email: z.string().email(), role: z.enum(['admin', 'user']) }))