0.2.1 • Published 5 years ago

@thrivesoft/typescript-rest-swagger v0.2.1

Weekly downloads
3
License
MIT
Repository
github
Last release
5 years ago

npm version Build Status Coverage Status Known Vulnerabilities

Swagger for Typescript-rest

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

NOTE

This is a temporary fork of typescript-rest-swagger to solve @Security decorator mismatch with typescript-rest. The changes made allow the @Security(['roles']) usage defined in typescript-rest, automatically discovering appropriate securityDefinitions. A pull request is open to merge this, if approved.

Table of Contents

Installation

npm install typescript-rest-swagger -g

Usage

swaggerGen -c ./swaggerConfig.json
swaggerGen -c ./swaggerConfig.json -t # load {cwd}/tsconfig.json
swaggerGen -c ./swaggerConfig.json -p ./tsconfig.json # load custom tsconfig.json

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

{
    "swagger": {
        "outputDirectory": "./dist",
        "entryFile": "./tests/data/apis.ts"
    }
}

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

{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "@/*": ["src/*"]
        }
    }
}

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:

import {Path, Accept, GET} from 'typescript-rest';
import {Tags} from 'typescript-rest-swagger';

@Path('mypath')
export class MyService {
    @GET
    @Tags('adminMethod', 'otheTag')
    @Accept('text/html')
    test( ): string {
        return 'OK';
    }

    @GET
    @Path('secondpath')
    test2( @QueryParam('testParam')test?: string ): Person {
        return {name: 'OK'};
    }
}

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

@Accept('text/plain')
@Path('mypath')
export class MyService {
    /**
     * This description will be used to describe the get operation of path '/mypath' on the generated swagger
     * @param test And this will describe the parameter test of this same operation
     */
    @GET
    @Path('secondpath')
    test2( @QueryParam('testParam')test?: string ): Person {
        return {name: 'OK'};
    }
}

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.

interface MyError {
   message: string
}

@Path('people')
class PeopleService {
  @Response<string>(200, 'Retrieve a list of people.')
  @Response<MyError>(401, 'The user is unauthorized.', {message: 'The user is not authorized to access this operation.'})
  @GET
  getPeople(@Param('name') name: string) {
     // ...
  }
}

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.

@Path('people')
class PeopleService {
  @Example<Array<Person>>([{
    name: 'Joe'
  }])
  @GET
  getPeople(@Param('name') name: string): Person[] {
     // ...
  }
}

@Tags

Add tags for a given method on generated swagger documentation.

@Path('people')
class PeopleService {
  @Tags('adiministrative', 'department1')
  @GET
  getPeople(@Param('name') name: string) {
     // ...
  }
}

@Security

Add a security constraint to generated method docs, referencing the security name and any scopes (or, roles) from securityDefinitions.

@Security can be used at the controller and method level; if defined on both, method security overwrites controller security. Multiple security schemes may be specified to require all of them.

When used with a single parameter, this will be interpreted as the scopes, which can be a string or an array. With two parameters, the first parameter should be the name of a securityDefinition defined in swagger.config.json. The second parameter is the scopes, which can be a string or an array of strings.

Note that where multiple scopes are specified, this implies that any one of those scopes will grant access.

@Path('secure')
class SecureService {
  @Security('basic_auth', [])
  @GET
  getBasicAuthContent(@Param('id') id: string) {
     // this method is only accessible by those authenticated with valid credentials for the basic_auth securityDefinition
  }
  
  @Security('read_profile')
  @GET
  getProfile(@Param('id') id: string) {
     // this method is only accessible by those authenticated with valid credentials with a grant for 'read_profile' for any securityDefinition containing the 'read_profile' scope
  }
  
  @Security('oauth',['read_profile'])
  @GET
  getOauthSpecificProfile(@Param('id') id: string) {
     // this method is only accessible by those authenticated with valid credentials for the oauth securityDefinition with a grant for the 'read_profile' scope
  }
}

@Produces

Document the produces property in generated swagger docs

@Path('people')
@Produces('text/html')
class PeopleService {
  @GET
  getPeople(@Param('name') name: string) {
     // ...
  }
}

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

@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.

class Person {
    @IsInt id: number;
}

@Path('people')
class PeopleService {
    @Path(':id')
    @GET
    getById(@PathParam('id') @IsLong id: number) {
        // ...
    }
}

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

interface Person {
    /**
     * The person's id
     * @IsInt
     */
    id: number;
}

SwaggerConfig.json

The swagger config file supports the following properties:

PropertyTypeDescription
basePathstringBase API path; e.g. the 'v1' in https://myapi.com/v1
consumesstringDefault consumes property for the entire API
descriptionstringAPI description; defaults to npm package description
entryFilestringThe entry point to your API
hoststringThe hostname to be informed in the generated swagger file
licensestringAPI license number; defaults to npm package license
namestringAPI name; defaults to npm package name
outputDirectorystringWhere to write the generated swagger file
producesstringDefault produces property for the entire API
versionstringAPI version number; defaults to npm package version
yamlbooleanGenerates the output also as an yaml file
specanyExtend generated swagger spec with this object. Note that generated properties will always take precedence over what get specified here
securityDefinitions*SecurityDefinitionSecurity 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.
collectionFormatstringDefault 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:

{
    [name: string]: {
        type: string;
        name?: string;
        authorizationUrl?: string;
        tokenUrl?: string;
        flow?: string;
        in?: string;
        scopes?: { [scopeName: string]: string; }
    }
}

See an example:

{
    "swagger": {
        "outputDirectory": "./dist",
        "entryFile": "./tests/data/apis.ts",
        "host": "localhost:3000",
        "version": "1.0",
        "name": "Typescript-rest Test API",
        "description": "a description",
        "license": "MIT",
        "basePath": "/v1",
        "securityDefinitions": {
            "api_key": {
                "type": "apiKey",
                "name": "access_token",
                "in": "query"
            }
        }
    }
}