ExisJS

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:

OptionTypeDefaultDescription
enabledbooleanfalseEnables or disables OpenAPI specification generation and documentation endpoints.
pathstring'/docs'Base URL path where the interactive documentation UI is mounted.
specPathstring'/docs/json'URL path where the raw OpenAPI 3.1.0 JSON specification is served.
titlestring'ExisJS API Documentation'API Title displayed in documentation headers and page metadata.
versionstring'1.0.0'Semantic version string of the API.
descriptionstringundefinedHigh-level API summary or Markdown description rendered in the UI header.
termsOfServicestringundefinedURL pointing to the API Terms of Service.
contactOpenApiInfo['contact']undefinedContact metadata (name, url, email).
licenseOpenApiInfo['license']undefinedLicense descriptor (name, url).
ui'swagger-ui' | 'scalar''swagger-ui'Interactive documentation UI renderer.
serversOpenApiServer[][{ url: '/' }]Array of server environment definitions (url, description, variables).
tagsOpenApiTag[][]Global tag descriptors for grouping endpoints (name, description, externalDocs).
securityRecord<string, string[]>[][]Global security requirements applied to all operations unless overridden.
securitySchemesRecord<string, SecuritySchemeObject>{}Reusable authentication schemes (apiKey, http Bearer, oauth2, openIdConnect).
customCssstringundefinedCustom CSS stylesheet injected into the documentation HTML.
customFaviconstringundefinedCustom favicon image URL.
transformSpec(spec: OpenApiSpec) => OpenApiSpec | voidundefinedHook 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) => void

Example

src/http/server.ts
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 & MethodDecorator
src/http/users/users.controller.ts
import { 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 }}): MethodDecorator
src/http/users/users.controller.ts
import { 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}): MethodDecorator
src/http/users/users.controller.ts
import { 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 & MethodDecorator
src/http/account/account.controller.ts
import { 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 & MethodDecorator
src/http/admin/admin.controller.ts
import { 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 & MethodDecorator
src/http/internal/internal.controller.ts
import { 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[]}): PropertyDecorator
src/http/users/dto/create-user.dto.ts
import { 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): OpenApiSpec

Example

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): string

Parameters

PropertyTypeDescription
config.ui'swagger-ui' | 'scalar'The chosen UI documentation theme.
config.specPathstringTarget URL path where the UI fetches the OpenAPI JSON specification.
config.titlestringDocument <title> tag content.
config.customCssstringInjected stylesheet string.
config.customFaviconstringInjected 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']) }))