### Parameter Examples Source: https://tsoa-community.github.io/docs/examples.html Shows how to provide examples for path parameters using JSDoc `@example` tags. ```APIDOC ## GET users/{userId} ### Description Retrieves a user by their ID and an optional name. ### Method GET ### Endpoint /users/{userId} ### Parameters #### Path Parameters - **userId** (UUID) - Required - The ID of the user to retrieve. - **Example 1**: "52907745-7672-470e-a803-a2f8feb52944" - **Example 2**: "e77ef155-bd12-46f0-8559-bf55f6dd4c63" #### Query Parameters - **name** (string) - Required - The name of the user. ### Response #### Success Response (200) - **User** - The user object. ### Response Example (Example for response body not provided in this snippet) ``` -------------------------------- ### Default Response Example Source: https://tsoa-community.github.io/docs/examples.html Demonstrates how to use the `@Example()` decorator to provide an example for the default response of an API endpoint. ```APIDOC ## GET users/{userId} ### Description Retrieves a user by their ID and an optional name. ### Method GET ### Endpoint /users/{userId} ### Parameters #### Path Parameters - **userId** (UUID) - Required - The ID of the user to retrieve. #### Query Parameters - **name** (string) - Required - The name of the user. ### Response #### Success Response (200) - **User** - The user object. ### Response Example ```json { "id": "52907745-7672-470e-a803-a2f8feb52944", "name": "tsoa user", "email": "hello@tsoa.com", "phoneNumbers": [], "status": "Happy" } ``` ``` -------------------------------- ### Model Examples Source: https://tsoa-community.github.io/docs/examples.html Demonstrates how to provide examples for model types (like UUID and User interface) using JSDoc `@example` tags. ```APIDOC ## Model: UUID ### Description Stringified UUIDv4. ### Type string ### Example "52907745-7672-470e-a803-a2f8feb52944" ## Model: User ### Description User objects allow you to associate actions performed in the system with the user that performed them. The User object contains common information across every user in the system regardless of status and role. ### Type object ### Example ```json { "id": "52907745-7672-470e-a803-a2f8feb52944", "name": "John Doe", "phoneNumbers": [] } ``` ### Properties - **id** (UUID) - Required - - **email** (string) - Optional - The email the user used to register his account - **name** (string) - Required - - **status** (Happy | Sad) - Optional - - **phoneNumbers** (string[]) - Required - ``` -------------------------------- ### Install Swagger UI Express Source: https://tsoa-community.github.io/docs/live-reloading.html Install swagger-ui-express and its types for serving Swagger UI documentation. ```bash yarn add swagger-ui-express yarn add -D @types/swagger-ui-express ``` -------------------------------- ### Provide Multiple Examples for a Path Parameter Source: https://tsoa-community.github.io/docs/examples.html Use the @example JSDoc tag to provide multiple examples for a path parameter. This helps in documenting various valid inputs for parameters like UUIDs. ```typescript @Route("users") export class UsersController extends Controller { /** * @example userId "52907745-7672-470e-a803-a2f8feb52944" * @example userId "e77ef155-bd12-46f0-8559-bf55f6dd4c63" */ @Get("{userId}") public async getUser( @Path() userId: UUID, @Query() name: string ): Promise { return new UsersService().get(userId, name); } } ``` -------------------------------- ### Install nodemon and ts-node Source: https://tsoa-community.github.io/docs/live-reloading.html Install nodemon, ts-node, and concurrently as development dependencies for live reloading. ```bash yarn add -D nodemon ts-node concurrently ``` -------------------------------- ### Add Example Response with @Example Decorator Source: https://tsoa-community.github.io/docs/examples.html Use the @Example decorator to specify an example response for a route. This is useful for documenting default responses and can be applied to other responses using the third argument of the @Response decorator. ```typescript import { Controller, Route, Get, Path, Query, Example } from "tsoa"; import { User } from "../models/User"; import { UUID } from "../types/UUID"; import { UsersService } from "../services/UsersService"; @Route("users") export class UsersController extends Controller { @Example({ id: "52907745-7672-470e-a803-a2f8feb52944", name: "tsoa user", email: "hello@tsoa.com", phoneNumbers: [], status: "Happy", }) @Get("{userId}") public async getUser( @Path() userId: UUID, @Query() name: string ): Promise { return new UsersService().get(userId, name); } } ``` -------------------------------- ### Define User Interface with Example Source: https://tsoa-community.github.io/docs/examples.html Define an interface for your models, such as User. Use JSDoc @example to provide a sample JSON object for the model. Ensure object and array examples are in correct JSON format to avoid errors during OAS generation. OpenAPI 2 and 3 only support a single example per model. ```typescript /** * User objects allow you to associate actions performed in the system with the user that performed them. * The User object contains common information across every user in the system regardless of status and role. * * * @example { * "id": "52907745-7672-470e-a803-a2f8feb52944", * "name": "John Doe", * "phoneNumbers": [] * } */ export interface User { id: UUID; /** * The email the user used to register his account */ email?: string; name: string; status?: "Happy" | "Sad"; phoneNumbers: string[]; } ``` -------------------------------- ### Install Multer for File Uploads Source: https://tsoa-community.github.io/docs/file-upload.html Install multer and its types for Node.js environments to enable file upload functionality. ```bash yarn add multer yarn add -D @types/multer ``` -------------------------------- ### Add TSOA Build and Start Scripts to package.json Source: https://tsoa-community.github.io/docs/getting-started.html Recommended scripts for package.json to automate building TSOA routes, compiling TypeScript, and starting the server. ```json "main": "build/src/server.js", "scripts": { "build": "tsoa spec-and-routes && tsc", "start": "node build/src/server.js" }, ``` -------------------------------- ### Parameter Description Example Source: https://tsoa-community.github.io/docs/descriptions.html This example demonstrates adding descriptions to parameters using JSDoc `@param` tags. These descriptions enhance clarity for both developers and API consumers. ```APIDOC ## GET /users/{userId} ### Description Retrieves the details of an existing user. Supply the unique user ID from either and receive corresponding user details. ### Method GET ### Endpoint /users/{userId} ### Parameters #### Path Parameters - **userId** (number) - Required - The user's identifier - **name** (string) - Optional - Provide a username to display ### Response #### Success Response (200) - **User** (User) - Description of the User object ### Request Example ```json { "userId": 123, "name": "John Doe" } ``` ### Response Example ```json { "id": 123, "email": "john.doe@example.com", "name": "John Doe", "status": "Happy", "phoneNumbers": ["123-456-7890"] } ``` ``` -------------------------------- ### Endpoint Description Example Source: https://tsoa-community.github.io/docs/descriptions.html This example shows how to add a description to an API endpoint using JSDoc. This description will be visible in editors and in the generated OpenAPI specification. ```APIDOC ## GET /users/{userId} ### Description Retrieves the details of an existing user. Supply the unique user ID from either and receive corresponding user details. ### Method GET ### Endpoint /users/{userId} ### Parameters #### Path Parameters - **userId** (number) - Required - The user's identifier #### Query Parameters - **name** (string) - Optional - Provide a username to display ### Response #### Success Response (200) - **User** (User) - Description of the User object ### Request Example ```json { "userId": 123, "name": "John Doe" } ``` ### Response Example ```json { "id": 123, "email": "john.doe@example.com", "name": "John Doe", "status": "Happy", "phoneNumbers": ["123-456-7890"] } ``` ``` -------------------------------- ### Using UploadedFile / UploadedFiles Decorators (Koa) Source: https://tsoa-community.github.io/docs/file-upload.html This example shows how to handle file uploads in a Koa application using TSOA decorators. It's similar to the Express example but uses Koa's `File` type for uploaded files. ```APIDOC ## POST /files/uploadFile ### Description Handles file uploads using decorators for Koa. ### Method POST ### Endpoint /files/uploadFile ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **title** (string) - Required - The title of the upload. - **description** (string) - Required - The description of the upload. - **files** (File[]) - Required - An array of uploaded files. - **file** (File) - Required - A single uploaded file. ### Request Example ```typescript import { Post, Route, FormField, UploadedFiles, UploadedFile } from "tsoa"; @Route("files") export class FilesController { @Post("uploadFile") public async uploadFile( @FormField() title: string, @FormField() description: string, @UploadedFiles() files: File[], @UploadedFile() file: File, ): Promise { console.log(files); } } ``` ### Response #### Success Response (200) No specific response body defined in the example. #### Response Example None ``` -------------------------------- ### Model Description Example (Interface) Source: https://tsoa-community.github.io/docs/descriptions.html This example shows how to describe a TypeScript interface used as a model. The JSDoc description is translated into the OpenAPI schema. ```APIDOC ## Model: User ### Description User objects allow you to associate actions performed in the system with the user that performed them. The User object contains common information across every user in the system regardless of status and role. ### Properties - **id** (number) - Description of the user ID - **email** (string) - Description of the user's email - **name** (string) - Description of the user's name - **status** (string) - Optional - Description of the user's status (e.g., "Happy", "Sad") - **phoneNumbers** (array[string]) - Description of the user's phone numbers ``` -------------------------------- ### Add development scripts to package.json Source: https://tsoa-community.github.io/docs/live-reloading.html Add 'dev', 'build', and 'start' scripts to your package.json for streamlined development workflows. ```diff { "name": "starter", "version": "0.0.1", + "scripts": { + "dev": "concurrently \"nodemon\" \"nodemon -x tsoa spec-and-routes\"", + "build": "tsoa spec-and-routes && tsc", + "start": "node build/src/server.js" + }, "dependencies": { // ... } ``` -------------------------------- ### Example IoC Module Implementation Source: https://tsoa-community.github.io/docs/di.html Implement an IoC module that exports either a pre-configured container or a factory function. This module will be used by tsoa to resolve controller instances. ```typescript // src/ioc.ts import { IocContainer, IocContainerFactory } from "@tsoa/runtime"; import { Container } from "di-package"; // Assign a container to `iocContainer`. const iocContainer = new Container(); // Or assign a function with to `iocContainer`. const iocContainer: IocContainerFactory = function ( request: Request ): IocContainer { const container = new Container(); container.bind(request); return container; }; // export according to convention export { iocContainer }; ``` -------------------------------- ### typescript-ioc Controller Setup Source: https://tsoa-community.github.io/docs/di.html Set up a TSOA controller using `typescript-ioc`. The `@Inject` decorator is used for property injection, and `@Singleton` is used for service definition. ```typescript import { Route } from 'tsoa'; import { Inject, Singleton } from "typescript-ioc"; @Route('foo') export class FooController { @Inject private fooService: FooService ... } @Singleton export class FooService { } ``` -------------------------------- ### Controller with API Key Security Source: https://tsoa-community.github.io/docs/authentication.html Example controller method secured with an API key. The `userInfo` method uses the `@Security('api_key')` decorator. ```typescript import { Get, Route, Security, Response } from "tsoa"; @Route("secure") export class SecureController { @Response("Unexpected error") @Security("api_key") @Get("UserInfo") public async userInfo(@Request() request: any): Promise { return Promise.resolve(request.user); } @Security("jwt", ["admin"]) @Get("EditUser") public async userInfo(@Request() request: any): Promise { // Do something here } } ``` -------------------------------- ### Using UploadedFile / UploadedFiles Decorators (Express) Source: https://tsoa-community.github.io/docs/file-upload.html This example demonstrates how to use the `@UploadedFiles` and `@UploadedFile` decorators to handle file uploads in an Express application. It also shows how to access other form fields using `@FormField`. ```APIDOC ## POST /files/uploadFile ### Description Handles file uploads using decorators for Express. ### Method POST ### Endpoint /files/uploadFile ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **title** (string) - Required - The title of the upload. - **description** (string) - Required - The description of the upload. - **files** (Express.Multer.File[]) - Required - An array of uploaded files. - **file** (Express.Multer.File) - Required - A single uploaded file. ### Request Example ```typescript import { Post, Route, FormField, UploadedFiles, UploadedFile } from "tsoa"; @Route("files") export class FilesController { @Post("uploadFile") public async uploadFile( @FormField() title: string, @FormField() description: string, @UploadedFiles() files: Express.Multer.File[], @UploadedFile() file: Express.Multer.File, ): Promise { console.log(files); } } ``` ### Response #### Success Response (200) No specific response body defined in the example. #### Response Example None ``` -------------------------------- ### Implement Users Service Source: https://tsoa-community.github.io/docs/getting-started.html Provides a UsersService class with methods to get a user by ID and name, and to create a new user using provided creation parameters. The create method generates a random ID for the new user. ```ts export class UsersService { public get(id: number, name?: string): User { return { id, email: "jane@doe.com", name: name ?? "Jane Doe", status: "Happy", phoneNumbers: [], }; } public create(userCreationParams: UserCreationParams): User { return { id: Math.floor(Math.random() * 10000), // Random status: "Happy", ...userCreationParams, }; } } ``` -------------------------------- ### Custom Multer Upload (Koa) Source: https://tsoa-community.github.io/docs/file-upload.html This example shows how to implement a custom file upload handler in a Koa application using multer. It demonstrates how to integrate multer with Koa's request context to process multipart/form-data. ```APIDOC ## POST /files/uploadFile ### Description Handles custom file uploads using multer directly within a Koa controller. ### Method POST ### Endpoint /files/uploadFile ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **randomFileIsHere** (buffer) - Required - The uploaded file content. ### Request Example ```typescript import { Post, Request, Route } from "tsoa"; import { Request as KoaRequest } from "koa"; import multer from "multer"; @Route("files") export class FilesController { @Post("uploadFile") public async uploadFile(@Request() request: KoaRequest): Promise { const multer = multer().single("file"); await multer(request.ctx, async () => null); const multerSingle = multer().single("randomFileIsHere"); // file will be in request.randomFileIsHere, it is a buffer return {}; } } ``` ### Response #### Success Response (200) - **any** - An empty object is returned. #### Response Example ```json { "example": "{}" } ``` ``` -------------------------------- ### Reusable Type Alias Description Example (UUID) Source: https://tsoa-community.github.io/docs/descriptions.html This example illustrates using a type alias with JSDoc for reusable descriptions, such as a UUID format. This description is then applied wherever the type alias is used. ```APIDOC ## Type Alias: UUID ### Description Stringified UUIDv4. See [RFC 4112](https://tools.ietf.org/html/rfc4122) ### Pattern `[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-4[0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}` ### Format uuid ``` -------------------------------- ### InversifyJS IoC Container Setup Source: https://tsoa-community.github.io/docs/di.html Set up an InversifyJS container for use with tsoa. This involves creating the container, decorating the base Controller class as injectable, and loading necessary Inversify modules. ```typescript // src/ioc.ts import { Container, decorate, injectable } from "inversify"; import { buildProviderModule } from "inversify-binding-decorators"; import { Controller } from "tsoa"; // Create a new container tsoa can use const iocContainer = new Container(); decorate(injectable(), Controller); // Makes tsoa's Controller injectable // make inversify aware of inversify-binding-decorators iocContainer.load(buildProviderModule()); // export according to convention export { iocContainer }; ``` -------------------------------- ### Custom Multer Upload (Express) Source: https://tsoa-community.github.io/docs/file-upload.html This example demonstrates how to implement a custom file upload handler in an Express application using multer directly within the controller. It shows how to access the uploaded file buffer from the request. ```APIDOC ## POST /files/uploadFile ### Description Handles custom file uploads using multer directly within an Express controller. ### Method POST ### Endpoint /files/uploadFile ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **file** (buffer) - Required - The uploaded file content. ### Request Example ```typescript import { Post, Request, Route } from "tsoa"; import express from "express"; import multer from "multer"; @Route("files") export class FilesController { @Post("uploadFile") public async uploadFile(@Request() request: express.Request): Promise { await this.handleFile(request); // file will be in request.randomFileIsHere, it is a buffer return {}; } private handleFile(request: express.Request): Promise { const multerSingle = multer().single("file"); return new Promise((resolve, reject) => { multerSingle(request, undefined, async (error) => { if (error) { reject(error); } resolve(); }); }); } } ``` ### Response #### Success Response (200) - **any** - An empty object is returned. #### Response Example ```json { "example": "{}" } ``` ``` -------------------------------- ### Configure tsconfig.json Path Mapping for jQuery Source: https://tsoa-community.github.io/docs/path-mapping.html Specify module mappings in tsconfig.json. This example maps the 'jquery' module to its location relative to 'baseUrl'. Ensure 'baseUrl' is specified when using 'paths'. ```json { "compilerOptions": { "baseUrl": ".", // This must be specified if "paths" is. "paths": { "jquery": ["node_modules/jquery/dist/jquery"] // This mapping is relative to "baseUrl" } } } ``` -------------------------------- ### Express Authentication Middleware Source: https://tsoa-community.github.io/docs/authentication.html Example of an Express authentication middleware function that handles different security schemes. ```APIDOC ## Express Authentication Middleware ### Description An example of an Express authentication middleware. This function handles different security schemes based on `securityName` and `scopes` provided by the controller's `@Security` decorator. ### Method Signature ```typescript export function expressAuthentication( request: express.Request, securityName: string, scopes?: string[] ): Promise ``` ### Implementation Example ```typescript import * as express from "express"; import * as jwt from "jsonwebtoken"; export function expressAuthentication( request: express.Request, securityName: string, scopes?: string[] ): Promise { if (securityName === "api_key") { let token; if (request.query && request.query.access_token) { token = request.query.access_token; } if (token === "abc123456") { return Promise.resolve({ id: 1, name: "Ironman", }); } else { return Promise.reject({}); } } if (securityName === "jwt") { const token = request.body.token || request.query.token || request.headers["x-access-token"]; return new Promise((resolve, reject) => { if (!token) { reject(new Error("No token provided")); } jwt.verify(token, "[secret]", function (err: any, decoded: any) { if (err) { reject(err); } else { // Check if JWT contains all required scopes for (let scope of scopes) { if (!decoded.scopes.includes(scope)) { reject(new Error("JWT does not contain required scope.")); } } resolve(decoded); } }); }); } } ``` ``` -------------------------------- ### Use JSDoc @summary for Method Descriptions Source: https://tsoa-community.github.io/docs/descriptions.html This TypeScript code demonstrates how to use the JSDoc @summary tag to provide a concise description for a controller method. The example shows a verbose description followed by a short summary. ```typescript /** * A very long, verbose, wordy, long-winded, tedious, verbacious, tautological, * profuse, expansive, enthusiastic, redundant, flowery, eloquent, articulate, * loquacious, garrulous, chatty, extended, babbling description. * @summary A concise summary. */ @Get('SummaryMethod') public async summaryMethod(): Promise { return new ModelService().getModel(); } ``` -------------------------------- ### Define UUID Type with Pattern and Example Source: https://tsoa-community.github.io/docs/examples.html Define a custom type like UUID using a TypeScript type alias. Use JSDoc annotations like @pattern for regex validation and @example to provide a sample value. Note that OpenAPI 2 only supports a single example per property. ```typescript /** * Stringified UUIDv4. * See [RFC 4112](https://tools.ietf.org/html/rfc4112) * @pattern [0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-4[0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12} * @example "52907745-7672-470e-a803-a2f8feb52944" */ export type UUID = string; ``` -------------------------------- ### Define a Simple Controller with TSOA Source: https://tsoa-community.github.io/docs/getting-started.html Define a controller for handling user-related requests with GET and POST methods. Uses path, query, and body parameters. Ensure controllers are named exports. ```typescript // src/users/usersController.ts import { Body, Controller, Get, Path, Post, Query, Route, SuccessResponse, } from "tsoa"; import { User } from "./user"; import { UsersService, UserCreationParams } from "./usersService"; @Route("users") export class UsersController extends Controller { @Get("{userId}") public async getUser( @Path() userId: number, @Query() name?: string ): Promise { return new UsersService().get(userId, name); } @SuccessResponse("201", "Created") // Custom success response @Post() public async createUser( @Body() requestBody: UserCreationParams ): Promise { this.setStatus(201); // set return status 201 new UsersService().create(requestBody); return; } } ``` -------------------------------- ### User Controller Definition Source: https://tsoa-community.github.io/docs/getting-started.html Defines a controller for managing users with GET and POST endpoints. ```APIDOC ## GET /users/{userId} ### Description Retrieves a user by their ID. Optionally filters by name. ### Method GET ### Endpoint /users/{userId} ### Parameters #### Path Parameters - **userId** (number) - Required - The ID of the user to retrieve. #### Query Parameters - **name** (string) - Optional - The name to filter users by. ### Response #### Success Response (200) - **User** (object) - The user object. ## POST /users ### Description Creates a new user. ### Method POST ### Endpoint /users ### Parameters #### Request Body - **requestBody** (UserCreationParams) - Required - The parameters for creating a user. ### Response #### Success Response (201) - **void** - Indicates successful creation. ### Response Example #### Success Response (201) (No response body expected for this success case) ``` -------------------------------- ### Define User Interface with Properties in tsoa Source: https://tsoa-community.github.io/docs/examples.html Defines a User interface with various property types including UUID, optional email, required name, status with example, and an array of strings for phone numbers. Note that the `id` property's example is ignored due to OpenAPI reference transformations. ```typescript export interface User { id: UUID; /** * The email the user used to register his account */ email?: string; name: string; /** * @example "Happy" */ status?: "Happy" | "Sad"; phoneNumbers: string[]; } ``` -------------------------------- ### Custom Success and Error Responses Source: https://tsoa-community.github.io/docs/examples.html Illustrates how to define custom success responses (e.g., 201 Created) and error responses (e.g., 422 Validation Failed) with examples. ```APIDOC ## POST users ### Description Adds a new user. Note that the demo API will not persist this data. ### Method POST ### Endpoint /users ### Parameters #### Request Body - **requestBody** (UserCreationParams) - Required - The parameters for creating a user. ### Response #### Success Response (201) - **void** - Indicates successful creation. #### Error Response (422) - **ValidateErrorJSON** - Details of the validation failure. ### Response Example (201) (No specific example provided in source, typically void or a success indicator) ### Response Example (422) ```json { "message": "Validation failed", "details": { "requestBody": { "message": "id is an excess property and therefore not allowed", "value": "52907745-7672-470e-a803-a2f8feb52944" } } } ``` ``` -------------------------------- ### Using IoC Container to get Controller Source: https://tsoa-community.github.io/docs/di.html When an IoC module is configured, tsoa will use it to retrieve controller instances. Ensure your IoC container or factory can handle requests to get controller types. ```typescript import { iocContainer } from "./the/path/to/the/module/from/tsoa.json"; iocContainer.get(FooController); ``` -------------------------------- ### TSyringe IOC Container Configuration for TSOA Source: https://tsoa-community.github.io/docs/di.html Configure TSyringe as the IOC container for TSOA by providing an `iocModule` in your `tsoa.json`. This example shows how to export the `iocContainer` object. ```typescript // src/lib/tsyringeTsoaIocContainer.ts // Target this file in your tsoa.json's "iocModule" property import { IocContainer } from '@tsoa/runtime'; import { container } from 'tsyringe'; export const iocContainer: IocContainer = { get: (controller: { prototype: T }): T => { return container.resolve(controller as never); }, }; ``` -------------------------------- ### Define IoC Container Interface and Factory Source: https://tsoa-community.github.io/docs/di.html Define the structure for your IoC container or a factory function that creates one. The container must implement the 'get' method, and the factory must accept a request object and return a container. ```typescript interface IocContainer { get(controller: { prototype: T }): T; } ``` ```typescript type IocContainerFactory = (request: unknown) => IocContainer; ``` -------------------------------- ### Initialize Project with Yarn Source: https://tsoa-community.github.io/docs/getting-started.html Sets up a new project directory, initializes npm and git, adds TSOA and Express dependencies, and initializes TypeScript configuration. ```shell # Create a new folder for our project mkdir tsoa-project cd tsoa-project # Create a package.json and initialize git git init yarn init -y # Add our dependencies yarn add tsoa express yarn add -D typescript @types/node @types/express # Initialize tsconfig.json yarn run tsc --init ``` -------------------------------- ### Configure nodemon for tsoa Source: https://tsoa-community.github.io/docs/live-reloading.html Create a nodemon.json file to specify the command for executing the server with ts-node and define files to watch for changes. ```json { "exec": "ts-node src/server.ts", "watch": ["src"], "ext": "ts" } ``` -------------------------------- ### Generate TSOA Routes and Compile TypeScript Source: https://tsoa-community.github.io/docs/getting-started.html Commands to generate the TSOA routes file and compile TypeScript code. Ensure the build directory exists. ```shell mkdir -p build # Create the build directory if it doesn't exist yarn run tsoa routes ``` ```shell yarn run tsc --outDir build --experimentalDecorators node build/src/server.js ``` -------------------------------- ### Configure Express Server with TSOA Routes Source: https://tsoa-community.github.io/docs/getting-started.html Set up an Express application to use TSOA by registering generated routes. Includes body parsing middleware. ```typescript // src/app.ts import express,{json, urlencoded} from "express"; import { RegisterRoutes } from "../build/routes"; export const app = express(); // Use body parser to read sent json payloads app.use( urlencoded({ extended: true, }) ); app.use(json()); RegisterRoutes(app); ``` ```typescript // src/server.ts import { app } from "./app"; const port = process.env.PORT || 3000; app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`) ); ``` -------------------------------- ### tsoa CLI Options for Route Generation Source: https://tsoa-community.github.io/docs/generating.html Configure route generation with options such as specifying a configuration file and base path. The default configuration file is 'tsoa.json'. ```bash Usage: tsoa routes [options] Options: --configuration, -c tsoa configuration file; default is tsoa.json in the working directory [string] --basePath Base API path [string] ``` -------------------------------- ### Configure Controller Discovery with Glob Patterns Source: https://tsoa-community.github.io/docs/routes.html Use `tsoa.json` to specify controller locations with minimatch glob patterns. This allows tsoa to automatically find controllers for OpenAPI documentation and route generation. ```json { "entryFile": "...", "routes": { "routesDir": "...", "middleware": "...", "controllerPathGlobs": [ "./dir-with-controllers/*", "./recursive-dir/**/*", "./custom-filerecursive-dir/**/*.controller.ts" ] } } ``` -------------------------------- ### OpenAPI Security Definitions and Route Configuration Source: https://tsoa-community.github.io/docs/authentication.html Configuration for OpenAPI security definitions and the path to the authentication middleware. ```APIDOC ## OpenAPI Security Definitions and Route Configuration ### Description Configure security definitions for OpenAPI and specify the authentication middleware path. ### Configuration ```json { "spec": { "securityDefinitions": { "api_key": { "type": "apiKey", "name": "access_token", "in": "query" }, "tsoa_auth": { "type": "oauth2", "authorizationUrl": "http://swagger.io/api/oauth/dialog", "flow": "implicit", "scopes": { "write:pets": "modify things", "read:pets": "read things" } } }, ... }, "routes": { "authenticationModule": "./authentication.ts", ... } } ``` ``` -------------------------------- ### Generate OAS and Routes using tsoa CLI Source: https://tsoa-community.github.io/docs/generating.html Use 'tsoa spec' to generate the OpenAPI Specification (OAS) and 'tsoa routes' to generate the routes. These are the basic commands for generating API artifacts. ```bash # generate OAS tsoa spec # generate routes tsoa routes ``` -------------------------------- ### Enable JSON module resolution Source: https://tsoa-community.github.io/docs/live-reloading.html Configure tsconfig.json to allow dynamic importing of JSON files, necessary for loading the OpenAPI specification. ```json { "compilerOptions": { "resolveJsonModule": true } } ``` -------------------------------- ### Hapi Authentication Middleware Source: https://tsoa-community.github.io/docs/authentication.html Placeholder for Hapi authentication middleware. ```APIDOC ## Hapi Authentication Middleware ### Description Placeholder for Hapi authentication middleware. The implementation is similar to the Express version. ### Method Signature ```typescript export function hapiAuthentication( request: hapi.Request, securityName: string, scopes?: string[] ): Promise ``` ``` -------------------------------- ### Catch-all Route Handler for Missing Routes Source: https://tsoa-community.github.io/docs/error-handling.html A catch-all route handler to gracefully handle requests to undefined routes. ```APIDOC ## Missing Route Handler ### Description This middleware is placed after all defined routes and handles requests to URLs that do not match any defined routes, returning a 404 Not Found response. ### Code ```typescript // app.ts import express, { Response as ExResponse, Request as ExRequest, NextFunction, } from "express"; // ... assuming RegisterRoutes is imported and app is an express instance RegisterRoutes(app); app.use(function notFoundHandler(_req, res: ExResponse) { res.status(404).send({ message: "Not Found", }); }); // Global error handler would typically follow app.use(function errorHandler(...)); ``` ``` -------------------------------- ### tsoa CLI Options for OAS Generation Source: https://tsoa-community.github.io/docs/generating.html Configure OAS generation with options like specifying a configuration file, API host, and base path. The default configuration file is 'tsoa.json'. ```bash Usage: tsoa spec [options] Options: --configuration, -c tsoa configuration file; default is tsoa.json in the working directory [string] --host API host [string] --basePath Base API path [string] ``` -------------------------------- ### Koa Authentication Middleware Source: https://tsoa-community.github.io/docs/authentication.html Placeholder for Koa authentication middleware. ```APIDOC ## Koa Authentication Middleware ### Description Placeholder for Koa authentication middleware. The implementation is similar to the Express version. ### Method Signature ```typescript export function koaAuthentication( request: Request, securityName: string, scopes?: string[] ): Promise ``` ``` -------------------------------- ### Catch-all Route Handler for Missing Routes Source: https://tsoa-community.github.io/docs/error-handling.html Add a catch-all route handler to gracefully manage requests for undefined URLs, returning a 404 Not Found response. ```typescript // app.ts import express, { Response as ExResponse, Request as ExRequest, NextFunction, } from "express"; // ... RegisterRoutes(app) app.use(function notFoundHandler(_req, res: ExResponse) { res.status(404).send({ message: "Not Found", }); }); app.use(function errorHandler( // ... ``` -------------------------------- ### OpenAPI Definition for File Upload Source: https://tsoa-community.github.io/docs/file-upload.html This snippet shows a sample OpenAPI definition for a file upload endpoint, specifying `multipart/form-data` and the file parameter. ```APIDOC ```json { "spec": { "...": "...", "specMerging": "recursive", "spec": { "paths": { "/files/uploadFile": { "post": { "consumes": [ "multipart/form-data" ], "parameters": [ { "in": "formData", "name": "randomFileIsHere", "required": true, "type": "file" } ] } } } } }, "routes": { "...": "..." } } ``` ``` -------------------------------- ### Configure tsoa.json for Path Mapping Source: https://tsoa-community.github.io/docs/path-mapping.html Provide a 'compilerOptions' property in tsoa.json to route configuration. This allows tsoa to use the same path mappings defined in tsconfig.json for its internal generators. ```json { "spec": { ... }, "routes": { ... }, "compilerOptions": { "baseUrl": "./path/to/base/url", "paths": { "exampleLib": "./path/to/example/lib" } } } ``` -------------------------------- ### tsoa Configuration for Tag Descriptions Source: https://tsoa-community.github.io/docs/decorators.html Configure tsoa.json to provide descriptions and external documentation links for tags used in the OpenAPI specification. ```json { "spec": { "tags": [ { "name": "User", "description": "Operations about users", "externalDocs": { "description": "Find out more about users", "url": "http://swagger.io" } } ], ... }, "routes": { ... } } ``` -------------------------------- ### Add Parameter Descriptions with JSDoc Source: https://tsoa-community.github.io/docs/descriptions.html Enhance endpoint descriptions by adding JSDoc `@param` tags for each parameter. This provides specific details about each input, visible in editors and documentation. ```typescript import { Controller, Route, Get, Path, Query } from "tsoa"; @Route("users") export class UsersController extends Controller { /** * Retrieves the details of an existing user. * Supply the unique user ID from either and receive corresponding user details. * @param userId The user's identifier * @param name Provide a username to display */ @Get("{userId}") public async getUser( @Path() userId: number, @Query() name?: string ): Promise { return new UsersService().get(userId, name); } } ``` -------------------------------- ### Expose Swagger UI endpoint Source: https://tsoa-community.github.io/docs/live-reloading.html Add an Express route to serve Swagger UI, dynamically generating HTML from the OpenAPI specification file. ```typescript // src/app.ts import express, { Response as ExResponse, Request as ExRequest } from "express"; import swaggerUi from "swagger-ui-express"; // ... app.use("/docs", swaggerUi.serve, async (_req: ExRequest, res: ExResponse) => { return res.send( swaggerUi.generateHTML(await import("../build/swagger.json")) ); }); ``` -------------------------------- ### Programmatic Generation of Routes and OAS with tsoa Source: https://tsoa-community.github.io/docs/generating.html Generate OAS and routes programmatically using tsoa's imported functions. Configure options like basePath, entryFile, specVersion, outputDirectory, and controllerPathGlobs. ```typescript import { generateRoutes, generateSpec, ExtendedRoutesConfig, ExtendedSpecConfig, } from "tsoa"; (async () => { const specOptions: ExtendedSpecConfig = { basePath: "/api", entryFile: "./api/server.ts", specVersion: 3, outputDirectory: "./api/dist", controllerPathGlobs: ["./routeControllers/**/*Controller.ts"], }; const routeOptions: ExtendedRoutesConfig = { basePath: "/api", entryFile: "./api/server.ts", routesDir: "./api", }; await generateSpec(specOptions); await generateRoutes(routeOptions); })(); ``` -------------------------------- ### Define User Creation Parameters Type Source: https://tsoa-community.github.io/docs/getting-started.html Creates a TypeScript Pick type for user creation parameters, selecting only 'email', 'name', and 'phoneNumbers' from the User interface. This excludes the 'id' and 'status' fields for creation. ```ts // src/users/usersService.ts import { User } from "./user"; // A post request should not contain an id. export type UserCreationParams = Pick; ``` -------------------------------- ### typescript-ioc Application Entry Point Source: https://tsoa-community.github.io/docs/di.html Ensure that controllers are imported in your application's entry point (`index.ts`) when using `typescript-ioc` to link them into the application. ```typescript import "./controllers/fooController.ts" ... ``` -------------------------------- ### Manually Reference Controllers in App Entry File Source: https://tsoa-community.github.io/docs/routes.html Import controller files directly in your application's entry file to ensure tsoa crawls them for the `@Route` decorator. This method can improve route generation speed. ```typescript import * as methodOverride from "method-override"; import * as express from "express"; import * as bodyParser from "body-parser"; import { RegisterRoutes } from "./routes"; // ######################################################################## // controllers need to be referenced in order to get crawled by the generator import "./users/usersController"; // ######################################################################## const app = express(); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(methodOverride()); RegisterRoutes(app); app.listen(3000); ``` -------------------------------- ### Add @tsoa/runtime with pnpm Source: https://tsoa-community.github.io/docs/getting-started.html Explicitly adds the @tsoa/runtime dependency when using pnpm, which is necessary for generated routes due to pnpm's symlinked node_modules structure. ```shell # Explicitely add @tsoa/runtime with pnpm as it will be needed by generated routes pnpm add @tsoa/runtime ``` -------------------------------- ### Hapi Authentication Middleware Stub Source: https://tsoa-community.github.io/docs/authentication.html Placeholder for Hapi authentication middleware implementation. The logic is similar to Express. ```typescript import * as hapi from "@hapi/hapi"; export function hapiAuthentication( request: hapi.Request, securityName: string, scopes?: string[] ): Promise { // See above } ``` -------------------------------- ### Koa Authentication Middleware Stub Source: https://tsoa-community.github.io/docs/authentication.html Placeholder for Koa authentication middleware implementation. The logic is similar to Express. ```typescript import { Request } from "koa"; export function koaAuthentication( request: Request, securityName: string, scopes?: string[] ): Promise { // See above } ``` -------------------------------- ### TSyringe Controller with Dependency Injection Source: https://tsoa-community.github.io/docs/di.html Create a TSOA controller that injects a service using TSyringe. The `@injectable()` decorator marks the class for dependency injection, and the service is injected via the constructor. ```typescript // src/controllers/FooController.ts import { Controller, Route } from 'tsoa'; import { injectable } from 'tsyringe'; import { FooService } from '../services/FooService'; // ... @injectable() @Route('foo') export class FooController extends Controller { constructor(private fooService: FooService) { super(); } // ... } ``` -------------------------------- ### Enable Decorator Metadata in tsconfig.json Source: https://tsoa-community.github.io/docs/custom-middlewares.html To use custom middleware and other decorators, ensure that 'experimentalDecorators' and 'emitDecoratorMetadata' are enabled in your tsconfig.json. ```json { "compilerOptions": { // ... "experimentalDecorators": true, "emitDecoratorMetadata": true, // ... } } ``` -------------------------------- ### Add Endpoint Description with JSDoc Source: https://tsoa-community.github.io/docs/descriptions.html Use JSDoc comments above controller methods to provide descriptions for API endpoints. These descriptions appear in editor tooltips and the generated OpenAPI specification. ```typescript import { Controller, Route, Get, Path, Query } from "tsoa"; @Route("users") export class UsersController extends Controller { /** * Retrieves the details of an existing user. * Supply the unique user ID from either and receive corresponding user details. */ @Get("{userId}") public async getUser( @Path() userId: number, @Query() name?: string ): Promise { return new UsersService().get(userId, name); } } ``` -------------------------------- ### SecureController - UserInfo Endpoint Source: https://tsoa-community.github.io/docs/authentication.html An endpoint to retrieve user information, secured by an API key. ```APIDOC ## GET /secure/UserInfo ### Description Retrieves user information. This endpoint is protected by the `api_key` security scheme. ### Method GET ### Endpoint `/secure/UserInfo` ### Parameters #### Query Parameters - **access_token** (string) - Required - The API key for authentication. ### Response #### Success Response (200) - **id** (number) - The user's ID. - **name** (string) - The user's name. ### Request Example ```bash GET /secure/UserInfo?access_token=abc123456 ``` ### Response Example ```json { "id": 1, "name": "Ironman" } ``` ``` -------------------------------- ### Configure tsoa to use an IoC module Source: https://tsoa-community.github.io/docs/di.html Reference your DI container's module in the tsoa configuration file by setting the 'iocModule' property. This tells tsoa where to find the module responsible for creating controllers. ```json { "entryFile": "...", "spec": { ... }, "routes": { "routesDir": "...", "middleware": "...", "iocModule": "src/ioc", ... } } ``` -------------------------------- ### InversifyJS Singleton Scope Provider Source: https://tsoa-community.github.io/docs/di.html Create a convenience decorator for InversifyJS to easily define services or controllers that should be singletons. This simplifies the process of managing singleton scopes. ```typescript // src/util/provideSingleton.ts import { fluentProvide } from "inversify-binding-decorators"; import { interfaces } from "inversify"; export const provideSingleton = function ( identifier: interfaces.ServiceIdentifier ) { return fluentProvide(identifier).inSingletonScope().done(); }; ``` -------------------------------- ### TSyringe Singleton Service Definition Source: https://tsoa-community.github.io/docs/di.html Define a service using TSyringe's `@singleton()` decorator. This ensures that only one instance of the service is created and reused. ```typescript // src/services/FooService.ts import { singleton } from 'tsyringe'; // ... @singleton() export class FooService { // ... } ```