TS 中文文档 TS 中文文档
指南
GitHub (opens new window)
指南
GitHub (opens new window)
  • 入门教程

    • TypeScript 手册
    • 基础知识
    • 日常类型
    • 类型缩小
    • 更多关于函数
    • 对象类型
    • 从类型创建类型
    • 泛型
    • Keyof 类型运算符
    • Typeof 类型运算符
    • 索引访问类型
    • 条件类型
    • 映射类型
    • 模板字面类型
    • 类
    • 模块
  • 参考手册

  • 项目配置

Master Workflow

Swagger for Typescript-rest


This is a tool to generate swagger files from a typescript-rest project.

Table of Contents

Swagger for Typescript-rest
Installation
Usage
Swagger Decorators
@Response
@Example
@Tags
@Consumes
@Produces
@Hidden
@IsInt, @IsLong, @IsFloat, @IsDouble

SwaggerConfig.json

Installation


  1. ``` shell
  2. npm install typescript-rest-swagger -g
  3. ```

Usage


  1. ``` shell
  2. swaggerGen -c ./swaggerConfig.json
  3. swaggerGen -c ./swaggerConfig.js #.js files are also allowed as config files
  4. swaggerGen -c ./swaggerConfig.json -t # load {cwd}/tsconfig.json
  5. swaggerGen -c ./swaggerConfig.json -p ./tsconfig.json # load custom tsconfig.json
  6. ```

Where the swaggerConfig.json file, contains settings about the swagger generation. For example:

  1. ``` json
  2. {
  3.     "swagger": {
  4.         "outputDirectory": "./dist",
  5.         "entryFile": "./tests/data/apis.ts"
  6.     }
  7. }
  8. ```

Where the tsconfig.json file contains compilerOptions. For example:

  1. ``` json
  2. {
  3.     "compilerOptions": {
  4.         "baseUrl": ".",
  5.         "paths": {
  6.             "@/*": ["src/*"]
  7.         }
  8.     }
  9. }
  10. ```

For example above options are required for swaggerGen to understand relative imports like import something from '@/something'.

Swagger Decorators


The documentation will be generated consulting all typescript-rest decorators present on your code. However, there are some additional informations that can be provided, only with documentation purposes, through some other decorators present into this library.

Some examples:

  1. ``` ts
  2. import {Path, Accept, GET} from 'typescript-rest';
  3. import {Tags} from 'typescript-rest-swagger';

  4. @Path('mypath')
  5. export class MyService {
  6.     @GET
  7.     @Tags('adminMethod', 'otheTag')
  8.     @Accept('text/html')
  9.     test( ): string {
  10.         return 'OK';
  11.     }

  12.     @GET
  13.     @Path('secondpath')
  14.     test2( @QueryParam('testParam')test?: string ): Person {
  15.         return {name: 'OK'};
  16.     }
  17. }
  18. ```

It is also important to observe that all JsDoc provided on your methods, classes, and parameters is outputed into the generated swagger file:

  1. ``` ts
  2. @Accept('text/plain')
  3. @Path('mypath')
  4. export class MyService {
  5.     /**
  6.      * This description will be used to describe the get operation of path '/mypath' on the generated swagger
  7.      * @param test And this will describe the parameter test of this same operation
  8.      */
  9.     @GET
  10.     @Path('secondpath')
  11.     test2( @QueryParam('testParam')test?: string ): Person {
  12.         return {name: 'OK'};
  13.     }
  14. }
  15. ```

These are the available swagger decorators, provided by typescript-rest-swagger:

@Response


A decorator to document the responses that a given service method can return. It is used to generate documentation for the REST service.

  1. ``` ts
  2. interface MyError {
  3.    message: string
  4. }

  5. @Path('people')
  6. class PeopleService {
  7.   @Response<string>(200, 'Retrieve a list of people.')
  8.   @Response<MyError>(401, 'The user is unauthorized.', {message: 'The user is not authorized to access this operation.'})
  9.   @GET
  10.   getPeople(@Param('name') name: string) {
  11.      // ...
  12.   }
  13. }
  14. ```

A Default response is already created in swagger documentation from the method return analisys. So any response declared through this decorator is an additional response created.

@Example


Used to provide an example of method return to be added into the method response section of the generated documentation for this method.

  1. ``` ts
  2. @Path('people')
  3. class PeopleService {
  4.   @Example<Array<Person>>([{
  5.     name: 'Joe'
  6.   }])
  7.   @GET
  8.   getPeople(@Param('name') name: string): Person[] {
  9.      // ...
  10.   }
  11. }
  12. ```

@Tags


Add tags for a given method on generated swagger documentation.

  1. ``` ts
  2. @Path('people')
  3. class PeopleService {
  4.   @Tags('adiministrative', 'department1')
  5.   @GET
  6.   getPeople(@Param('name') name: string) {
  7.      // ...
  8.   }
  9. }
  10. ```

@Consumes


Document the consumes property in generated swagger docs

  1. ``` ts
  2. @Path('people')
  3. @Consumes('text/html')
  4. class PeopleService {
  5.   @PUT
  6.   createPeople(@Param('name') name: string, people: People) {
  7.      // ...
  8.   }
  9. }
  10. ```

@Produces


Document the produces property in generated swagger docs

  1. ``` ts
  2. @Path('people')
  3. @Produces('text/html')
  4. class PeopleService {
  5.   @GET
  6.   getPeople(@Param('name') name: string) {
  7.      // ...
  8.   }
  9. }
  10. ```

A Default produces is already created in swagger documentation from the method return analisys. You can use this decorator to override this default produces.

@Hidden


Allow to hide some APIs from swagger docs (ex: test or dev APIs, etc ...). This decorator can be applied for the whole class or only a single method

  1. ``` ts
  2. @Path('people')
  3. @Hidden()
  4. class PeopleService {
  5.   @GET
  6.   getPeople(@Param('name') name: string) {
  7.      // ...
  8.   }
  9. }
  10. ```

@IsInt, @IsLong, @IsFloat, @IsDouble


Document the type of a number property or parameter in generated swagger docs. If no decorator is present, the number type defaults to double format.

  1. ``` ts
  2. class Person {
  3.     @IsInt id: number;
  4. }

  5. @Path('people')
  6. class PeopleService {
  7.     @Path(':id')
  8.     @GET
  9.     getById(@PathParam('id') @IsLong id: number) {
  10.         // ...
  11.     }
  12. }
  13. ```

Because decorators don't work on type and interface properties, this can also be specified as a JSDoc tag.

  1. ``` ts
  2. interface Person {
  3.     /**
  4.      * The person's id
  5.      * @IsInt
  6.      */
  7.     id: number;
  8. }
  9. ```

SwaggerConfig.json


The swagger config file supports the following properties:

Property Type Description
:--- :--- :---
basePath string Base API path; e.g. the 'v1' in https://myapi.com/v1
consumes [string] Default consumes property for the entire API
description string API description; defaults to npm package description
entryFile string or string[] The entry point to your API (it is possible to use glob patters)
outputFormat 'Swagger_2' or 'OpenApi_3' Inform if the generated spec will be in swagger 2.0 format or i open api 3.0
host string The hostname to be informed in the generated swagger file
license string API license number; defaults to npm package license
name string API name; defaults to npm package name
outputDirectory string Where to write the generated swagger file
produces [string] Default produces property for the entire API
version string API version number; defaults to npm package version
yaml boolean Generates the output also as an yaml file
spec any Extend generated swagger spec with this object. Note that generated properties will always take precedence over what get specified here
securityDefinitions *SecurityDefinition Security Definitions Object. A declaration of the security schemes available to be used in the specification. This does not enforce the security schemes on the operations and only serves to provide the relevant details for each scheme.
collectionFormat string Default collectionFormat property for the entire API. Possible values are csv, ssv, tsv, pipes, multi. If not specified, Swagger defaults to csv.

Where the SecurityDefinition contract is defined as:

  1. ``` ts
  2. {
  3.     [name: string]: {
  4.         type: string;
  5.         name?: string;
  6.         authorizationUrl?: string;
  7.         tokenUrl?: string;
  8.         flow?: string;
  9.         in?: string;
  10.         scopes?: { [scopeName: string]: string; }
  11.     }
  12. }
  13. ```

See an example:

  1. ``` json
  2. {
  3.     "swagger": {
  4.         "outputDirectory": "./dist",
  5.         "entryFile": "./controllers/*.ts",
  6.         "outputFormat": "openapi_3",
  7.         "host": "localhost:3000",
  8.         "version": "1.0",
  9.         "name": "Typescript-rest Test API",
  10.         "description": "a description",
  11.         "license": "MIT",
  12.         "basePath": "/v1",
  13.         "securityDefinitions": {
  14.             "api_key": {
  15.                 "type": "apiKey",
  16.                 "name": "access_token",
  17.                 "in": "query"
  18.             }
  19.         },
  20.         "ignore": [
  21.           "**/node_modules/**"
  22.         ]
  23.     }
  24. }
  25. ```

or in yaml format: See an example:

  1. ``` yaml
  2. swagger:
  3.   outputDirectory: ./dist
  4.   entryFile:
  5.     - ./controllers/*.ts
  6.   outputFormat: openapi_3
  7.   host: localhost:3000
  8.   version: 1.0
  9.   name: Typescript-rest Test API
  10.   description: A description
  11.   license: MIT
  12.   basePath: /v1
  13.   securityDefinitions:
  14.     api_key:
  15.       type: apiKey
  16.       name: access_token
  17.       in: query
  18.   ignore:
  19.     - /node_modules/**  
  20. ```
Last Updated: 2023-09-03 17:10:52