### Controller Example Source: https://github.com/typestack/routing-controllers/blob/develop/README.md A simple controller class with a GET method. This class should be placed in a file matching the pattern specified in `useExpressServer` or `useKoaServer`. ```typescript import { JsonController, Get } from "routing-controllers"; @JsonController() export class UserController { @Get("/users") getAll(): string { return "This returns all users"; } } ``` -------------------------------- ### Express Application Setup with Routing Controllers Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Create an Express server instance using `createExpressServer` and register your controllers. This example sets up the server to listen on port 3000. ```typescript // this shim is required import { createExpressServer } from 'routing-controllers'; import { UserController } from './UserController'; // creates express app, registers all controller routes and returns you express app instance const app = createExpressServer({ controllers: [UserController], // we specify controllers we want to use }); // run express application on port 3000 app.listen(3000); ``` -------------------------------- ### Basic Express Controller Example Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Define a controller with various HTTP methods (GET, POST, PUT, DELETE) using routing-controllers decorators. This example demonstrates basic route registration for user management. ```typescript import 'reflect-metadata'; import { Controller, Param, Body, Get, Post, Put, Delete } from 'routing-controllers'; @Controller() export class UserController { @Get('/users') getAll() { return 'This action returns all users'; } @Get('/users/:id') getOne(@Param('id') id: number) { return 'This action returns user #' + id; } @Post('/users') post(@Body() user: any) { return 'Saving user...'; } @Put('/users/:id') put(@Param('id') id: number, @Body() user: any) { return 'Updating a user...'; } @Delete('/users/:id') remove(@Param('id') id: number) { return 'Removing user...'; } } ``` -------------------------------- ### Install routing-controllers and reflect-metadata Source: https://github.com/typestack/routing-controllers/blob/develop/docs/lang/chinese/README.md Install the routing-controllers module and the necessary reflect-metadata library. Ensure reflect-metadata is imported before using routing-controllers. ```bash npm install routing-controllers npm install reflect-metadata ``` -------------------------------- ### Basic Usage with Express Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Demonstrates setting up routing-controllers with an Express application. Ensure Express is installed and imported. ```typescript import express from "express"; import { useExpressServer } from "routing-controllers"; const app = express(); useExpressServer(app, { routePrefix: "/api", controllers: [__dirname + "/controllers/*.js"], }); app.listen(3000, () => { console.log("Server listening on port 3000"); }); ``` -------------------------------- ### Install Koa 2 dependencies Source: https://github.com/typestack/routing-controllers/blob/develop/docs/lang/chinese/README.md Install the required dependencies for using routing-controllers with Koa 2, including koa, @koa/router, koa-bodyparser, and @koa/multer. Optional type declarations can also be installed. ```bash npm install koa @koa/router koa-bodyparser @koa/multer npm install -D @types/koa @types/koa-bodyparser ``` -------------------------------- ### Basic Usage with Koa Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Shows how to integrate routing-controllers with a Koa application. Koa should be installed and imported. ```typescript import Koa from "koa"; import { useKoaServer } from "routing-controllers"; const app = new Koa(); useKoaServer(app, { routePrefix: "/api", controllers: [__dirname + "/controllers/*.js"], }); app.listen(3000, () => { console.log("Server listening on port 3000"); }); ``` -------------------------------- ### Pre-configuring Express/Koa Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Illustrates how to use routing-controllers with an already configured Express or Koa application instance. This allows for more control over the server setup. ```typescript import express from "express"; import { useExpressServer } from "routing-controllers"; const app = express(); app.use(express.json()); // Example of pre-configuration useExpressServer(app, { controllers: [__dirname + "/controllers/*.js"], }); app.listen(3000, () => { console.log("Server listening on port 3000"); }); ``` -------------------------------- ### Install Express.js dependencies Source: https://github.com/typestack/routing-controllers/blob/develop/docs/lang/chinese/README.md Install the required dependencies for using routing-controllers with Express.js, including express, body-parser, and multer. Optional type declarations can also be installed. ```bash npm install express body-parser multer npm install -D @types/express @types/body-parser @types/multer ``` -------------------------------- ### Pre-configure Express Server with useExpressServer Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Use `useExpressServer` to integrate routing-controllers with an existing or custom-configured Express application. This allows for detailed server setup before starting the application. ```typescript import { useExpressServer } from 'routing-controllers'; let express = require('express'); // or you can import it if you have installed typings let app = express(); // your created express server // app.use() // you can configure it the way you want useExpressServer(app, { // register created express server in routing-controllers controllers: [UserController], // and configure it the way you need (controllers, validation, etc.) }); app.listen(3000); // run your express server ``` -------------------------------- ### Example Invalid User Creation Request and Response - JSON Source: https://context7.com/typestack/routing-controllers/llms.txt Demonstrates an example of sending invalid user data in a POST request and the corresponding 400 Bad Request response with detailed validation errors. This highlights how class-validator integration provides specific feedback on validation failures. ```json // POST /users with invalid data: // { "name": "J", "email": "invalid", "password": "weak" } // Response 400: // { // "errors": [ // { "property": "name", "constraints": { "minLength": "name must be longer than or equal to 2 characters" } }, // { "property": "email", "constraints": { "isEmail": "Please provide a valid email address" } }, // { "property": "password", "constraints": { "minLength": "Password must be at least 8 characters" } } // ] // } ``` -------------------------------- ### Create Express Server with Routing Controllers Source: https://context7.com/typestack/routing-controllers/llms.txt Use `createExpressServer` to set up an Express.js application with routing-controllers. Configure controllers, route prefix, CORS, validation, and class-transformer. The server starts listening on port 3000. ```typescript import 'reflect-metadata'; import { createExpressServer } from 'routing-controllers'; import { UserController } from './controllers/UserController'; // Create Express server with controllers const app = createExpressServer({ controllers: [UserController], routePrefix: '/api', cors: true, validation: true, classTransformer: true, defaults: { nullResultCode: 404, undefinedResultCode: 204, paramOptions: { required: true } } }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); }); // Expected: Express server starts with routes prefixed with /api // GET http://localhost:3000/api/users -> returns all users ``` -------------------------------- ### Register Compression Middleware Globally Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Integrate compression middleware globally for all controllers by registering it during server bootstrap. Ensure the 'compression' package is installed. ```typescript import { createExpressServer } from 'routing-controllers'; import { UserController } from './UserController'; // we need to "load" our controller before call createExpressServer. this is required let compression = require('compression'); let app = createExpressServer({ controllers: [UserController], }); // creates express app, registers all controller routes and returns you express app instance app.use(compression()); app.listen(3000); // run express application ``` -------------------------------- ### Use Compression Middleware Per-Action Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Apply compression middleware to a specific controller action. Ensure the 'compression' package is installed. ```typescript import { Controller, Get, Param, UseBefore } from "routing-controllers"; let compression = require("compression"); @Controller() export class UserController { @Get("/users/:id") @UseBefore(compression()) getOne(@Param("id") id: number) { // ... } } ``` -------------------------------- ### Use Compression Middleware Per-Controller Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Apply compression middleware to all actions within a specific controller. Ensure the 'compression' package is installed. ```typescript import { Controller, UseBefore } from 'routing-controllers'; let compression = require('compression'); @Controller() @UseBefore(compression()) export class UserController {} ``` -------------------------------- ### Injecting Services into Controllers with TypeDI Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Example of injecting services into controllers when using TypeDI. Controllers also need to be decorated with @Service() when using TypeDI version 0.9.0 or later. ```typescript @Controller() @Service() export class UsersController { constructor(private userRepository: UserRepository) {} // ... controller actions } ``` -------------------------------- ### Create Custom Parameter Decorator with routing-controllers Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Example of creating a custom parameter decorator, 'UserFromSession', to fetch user data from the request headers. It supports a 'required' option to enforce user presence. ```typescript import { createParamDecorator } from 'routing-controllers'; export function UserFromSession(options?: { required?: boolean }) { return createParamDecorator({ required: options && options.required ? true : false, value: action => { const token = action.request.headers['authorization']; return database.findUserByToken(token); }, }); } ``` -------------------------------- ### Define a basic Express Controller Source: https://github.com/typestack/routing-controllers/blob/develop/docs/lang/chinese/README.md Create a controller class using the @Controller decorator and define routes with HTTP method decorators like @Get, @Post, @Put, and @Delete. Use @Param and @Body decorators to access route parameters and request bodies. ```typescript import { Controller, Param, Body, Get, Post, Put, Delete } from 'routing-controllers'; @Controller() export class UserController { @Get('/users') getAll() { return 'This action returns all users'; } @Get('/users/:id') getOne(@Param('id') id: number) { return 'This action returns user #' + id; } @Post('/users') post(@Body() user: any) { return 'Saving user...'; } @Put('/users/:id') put(@Param('id') id: number, @Body() user: any) { return 'Updating a user...'; } @Delete('/users/:id') remove(@Param('id') id: number) { return 'Removing user...'; } } ``` -------------------------------- ### JSON Controller Example Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Use the `@JsonController` decorator for REST APIs that exclusively handle JSON. This ensures responses are always JSON and requests are parsed as JSON. ```typescript import { JsonController, Param, Body, Get, Post, Put, Delete } from 'routing-controllers'; @JsonController() export class UserController { @Get('/users') getAll() { return userRepository.findAll(); } @Get('/users/:id') getOne(@Param('id') id: number) { return userRepository.findById(id); } @Post('/users') post(@Body() user: User) { return userRepository.insert(user); } } ``` -------------------------------- ### Enable CORS with routing-controllers Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Enable Cross-Origin Resource Sharing (CORS) by setting the `cors` option to `true` or an options object in the `createExpressServer` configuration. Ensure the `cors` module is installed for your framework (e.g., `npm i cors` for Express). ```typescript import { createExpressServer } from 'routing-controllers'; import { UserController } from './UserController'; const app = createExpressServer({ cors: true, controllers: [UserController], }); app.listen(3000); ``` ```typescript import { createExpressServer } from 'routing-controllers'; import { UserController } from './UserController'; const app = createExpressServer({ cors: { // options from cors documentation }, controllers: [UserController], }); app.listen(3000); ``` -------------------------------- ### Define a Controller with CRUD Operations Source: https://context7.com/typestack/routing-controllers/llms.txt Use the `@Controller` decorator to define a class as a controller and its methods as route handlers. This example demonstrates GET, POST, PUT, and DELETE methods for user management with parameter and body decorators. ```typescript import { Controller, Get, Post, Put, Delete, Param, Body } from 'routing-controllers'; @Controller('/users') export class UserController { @Get() getAll() { return [ { id: 1, name: 'John Doe' }, { id: 2, name: 'Jane Smith' } ]; } @Get('/:id') getOne(@Param('id') id: number) { return { id, name: 'John Doe' }; } @Post() create(@Body() user: { name: string; email: string }) { return { id: 3, ...user }; } @Put('/:id') update(@Param('id') id: number, @Body() user: { name: string }) { return { id, ...user }; } @Delete('/:id') delete(@Param('id') id: number) { return { deleted: true, id }; } } // Expected routes: // GET /users -> returns all users // GET /users/1 -> returns user with id 1 // POST /users -> creates new user // PUT /users/1 -> updates user with id 1 // DELETE /users/1 -> deletes user with id 1 ``` -------------------------------- ### Loading Controllers from Directory Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Shows how to automatically load all controller files from a specified directory. Ensure the path is correct and controllers are exported. ```typescript import express from "express"; import { useExpressServer } from "routing-controllers"; const app = express(); useExpressServer(app, { controllers: [__dirname + "/controllers/**/*.ts"], // Loads all .ts files in controllers directory and subdirectories }); app.listen(3000, () => { console.log("Server listening on port 3000"); }); ``` -------------------------------- ### GET Request Decorator Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Use the @Get decorator to register a GET request to a specific route. Action options can specify response type (JSON or text). ```typescript @Get("/users") all() ``` -------------------------------- ### Using Existing Middleware Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Shows how to apply existing Express or Koa middleware to specific routes or globally using the `@UseMiddleware` decorator or server options. ```typescript import { Controller, Get, UseMiddleware } from "routing-controllers"; import * as basicAuth from 'express-basic-auth'; @Controller() export class ProtectedController { @Get("/protected") @UseMiddleware(basicAuth({ users: { admin: 'password' }, challenge: true })) getProtectedData(): string { return "This is protected data"; } } ``` -------------------------------- ### Load All Controllers from Directory Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Dynamically load all controllers from a specified directory by providing an array of directory paths to `createExpressServer` or `useExpressServer`. ```typescript import { createExpressServer } from 'routing-controllers'; import path from 'path'; createExpressServer({ controllers: [path.join(__dirname + '/controllers/*.js')], }).listen(3000); // register controllers routes in our express application ``` -------------------------------- ### Load Components from Directories Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Configure routing-controllers to load controllers, middlewares, and interceptors from specified directories using path joining and glob patterns. ```typescript import { createExpressServer } from 'routing-controllers'; import path from 'path'; createExpressServer({ controllers: [path.join(__dirname, '/controllers/**/*.js')], middlewares: [path.join(__dirname, '/middlewares/**/*.js')], interceptors: [path.join(__dirname, '/interceptors/**/*.js')], }).listen(3000); ``` -------------------------------- ### Parameter Decorators Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Demonstrates how to make parameters required and how routing-controllers handles parameter conversion using class-transformer. ```APIDOC ## POST /users ### Description This endpoint saves user data. The `user` body parameter is marked as required, meaning the request will fail if the user data is not provided. ### Method POST ### Endpoint /users ### Parameters #### Request Body - **user** (any) - Required - The user data to be saved. ### Request Example ```json { "example": "{\"name\": \"John Doe\", \"email\": \"john.doe@example.com\"}" } ``` ### Response #### Success Response (200) - **(response body)** - Details of the saved user or a success message. #### Response Example ```json { "example": "{\"id\": 1, \"name\": \"John Doe\", \"email\": \"john.doe@example.com\"}" } ``` ## Parameter Conversion ### Description When a class type is specified for a parameter decorated with a parameter decorator (e.g., `@BodyParam`, `@QueryParam`), routing-controllers uses `class-transformer` to instantiate that class from the request data. This allows for automatic validation and transformation of incoming data into strongly-typed objects. ### Method Any (GET, POST, PUT, DELETE, etc.) ### Endpoint Any ### Parameters #### Request Body / Query Parameters / Path Parameters - **(parameter)** (ClassType) - Required/Optional - Description of the parameter, where ClassType is a user-defined class. ### Request Example ```typescript import { Body, Post } from 'routing-controllers'; import { User } from './User'; // Assuming User is a class defined elsewhere @Post('/users') saveUser(@Body() user: User) { // 'user' will be an instance of the User class // ... } ``` ### Response #### Success Response (200) - **(response body)** - The result of the action. #### Response Example ```json { "example": "{\"message\": \"User created successfully\"}" } ``` ``` -------------------------------- ### createExpressServer Source: https://context7.com/typestack/routing-controllers/llms.txt Creates and configures an Express.js application with routing-controllers, automatically loading controllers, middlewares, and interceptors. ```APIDOC ## createExpressServer ### Description Creates and configures an Express.js application with all registered controllers, middlewares, and interceptors automatically loaded and routes registered based on decorator metadata. ### Method `createExpressServer` function ### Endpoint N/A (This function creates the server instance) ### Parameters - `options` (object) - Required - Configuration options for the server. - `controllers` (array) - Required - An array of controller classes. - `routePrefix` (string) - Optional - A prefix for all routes. - `cors` (boolean or object) - Optional - Enable CORS. - `validation` (boolean) - Optional - Enable request body validation. - `classTransformer` (boolean) - Optional - Enable class-transformer integration. - `defaults` (object) - Optional - Default options for responses and parameters. - `nullResultCode` (number) - Optional - HTTP status code for null results. - `undefinedResultCode` (number) - Optional - HTTP status code for undefined results. - `paramOptions` (object) - Optional - Default options for parameters. - `required` (boolean) - Optional - Whether parameters are required by default. ### Request Example ```typescript import 'reflect-metadata'; import { createExpressServer } from 'routing-controllers'; import { UserController } from './controllers/UserController'; const app = createExpressServer({ controllers: [UserController], routePrefix: '/api', cors: true, validation: true, classTransformer: true, defaults: { nullResultCode: 404, undefinedResultCode: 204, paramOptions: { required: true } } }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); }); ``` ### Response - `Express.Application` - The configured Express application instance. ### Response Example ``` // Express server starts with routes prefixed with /api // GET http://localhost:3000/api/users -> returns all users ``` ``` -------------------------------- ### Using Express Types for Request and Response Source: https://github.com/typestack/routing-controllers/blob/develop/README.md If you have installed typings for Express, you can use their specific types for the Request and Response objects for better type safety. ```typescript import { Request, Response } from 'express'; import { Controller, Req, Res, Get } from 'routing-controllers'; @Controller() export class UserController { @Get('/users') getAll(@Req() request: Request, @Res() response: Response) { return response.send('Hello response!'); } } ``` -------------------------------- ### Create Koa Server with Routing Controllers Source: https://context7.com/typestack/routing-controllers/llms.txt Use `createKoaServer` to initialize a Koa.js application with routing-controllers. Specify controllers, route prefix, CORS, and validation options. The server will listen on port 3000. ```typescript import 'reflect-metadata'; import { createKoaServer } from 'routing-controllers'; import { UserController } from './controllers/UserController'; // Create Koa server with controllers const app = createKoaServer({ controllers: [UserController], routePrefix: '/api', cors: true, validation: true }); app.listen(3000, () => { console.log('Koa server running on http://localhost:3000'); }); // Expected: Koa server starts with all controller routes registered // GET http://localhost:3000/api/users -> returns all users ``` -------------------------------- ### Inject Query Parameter with @QueryParam() Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Use the @QueryParam() decorator to inject a specific query string parameter by its name. The parameter is typed as a number in this example. ```typescript get(@QueryParam("id") id: number) ``` -------------------------------- ### Auto Validating Action Params Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Integrates with validation libraries (like class-validator) to automatically validate incoming request parameters. Requires `class-validator` and `class-transformer` to be installed. ```typescript import { Controller, Post, Body } from "routing-controllers"; import { IsString, IsEmail, MinLength } from "class-validator"; export class UserInput { @IsString() @MinLength(2) name: string; @IsEmail() email: string; } @Controller() export class ValidationController { @Post("/validate-user") createUser(userInput: UserInput): string { // If validation fails, routing-controllers automatically sends a 400 error return `User ${userInput.name} is valid`; } } ``` -------------------------------- ### Rendering Templates Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Shows how to render view templates (e.g., EJS, Pug) from a controller action. Requires a template engine and a `render` function to be configured. ```typescript import { Controller, Get, Render } from "routing-controllers"; @Controller() export class TemplateController { @Get("/render") @Render("my-template.ejs") // Renders 'my-template.ejs' renderTemplate(): object { return { message: "Hello from template!" }; } } ``` -------------------------------- ### Inject Uploaded File Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Demonstrates how to inject uploaded files using the @UploadedFile decorator and how to configure upload options. It also mentions @UploadedFiles for multiple files. ```APIDOC ## POST /files ### Description Saves a single uploaded file. ### Method POST ### Endpoint /files #### Request Body - **fileName** (any) - Required - The uploaded file. ### Request Example (Form data with a file field named 'fileName') ### Response #### Success Response (200) - **message** (string) - Confirmation message. ## POST /files/with-options ### Description Saves a single uploaded file with custom multer options. ### Method POST ### Endpoint /files/with-options #### Request Body - **fileName** (any) - Required - The uploaded file, with custom upload options applied. ### Request Example (Form data with a file field named 'fileName') ### Response #### Success Response (200) - **message** (string) - Confirmation message. ``` -------------------------------- ### Setup CurrentUserChecker for @CurrentUser Decorator Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Configure routing-controllers to use a custom currentUserChecker. This function is responsible for fetching and returning the user object based on request details, such as an authorization token. ```typescript import { createExpressServer, Action } from 'routing-controllers'; createExpressServer({ currentUserChecker: async (action: Action) => { // here you can use request/response objects from action // you need to provide a user object that will be injected in controller actions // demo code: const token = action.request.headers['authorization']; return getEntityManager().findOneByToken(User, token); }, }).listen(3000); ``` -------------------------------- ### Accessing Raw Request and Response Objects Source: https://context7.com/typestack/routing-controllers/llms.txt Demonstrates how to use @Req, @Res (for Express), and @Ctx (for Koa) decorators to access framework-specific request and response objects. ```APIDOC ## @Req, @Res, @Ctx Decorators for injecting the raw framework request and response objects. @Req and @Res are used with Express while @Ctx is used with Koa for accessing the context object. ### GET /raw/request-info **Description**: Retrieves information about the incoming request using the Express Request object. **Method**: GET **Endpoint**: /raw/request-info **Parameters**: **Request Body**: None **Response**: #### Success Response (200) - **method** (string) - The HTTP method of the request. - **url** (string) - The URL of the request. - **ip** (string) - The IP address of the client. - **headers** (object) - The request headers. #### Response Example ```json { "method": "GET", "url": "/raw/request-info", "ip": "127.0.0.1", "headers": { "host": "localhost:3000", "connection": "keep-alive" } } ``` ### GET /raw/custom-response **Description**: Demonstrates custom response handling using the Express Response object, setting headers and status code. **Method**: GET **Endpoint**: /raw/custom-response **Parameters**: **Request Body**: None **Response**: #### Success Response (200) - **custom** (boolean) - Indicates a custom response was generated. #### Response Example ```json { "custom": true } ``` ### POST /raw/file-download **Description**: Handles file download by setting appropriate response headers and sending file content. **Method**: POST **Endpoint**: /raw/file-download **Parameters**: #### Query Parameters - **filename** (string) - Optional. The name of the file to download. **Request Body**: None **Response**: #### Success Response (200) - The response will contain the file content and appropriate headers for download. ### GET /raw/redirect **Description**: Performs an HTTP redirect to a new location. **Method**: GET **Endpoint**: /raw/redirect **Parameters**: **Request Body**: None **Response**: #### Success Response (302) - Redirects the client to `/new-location`. ### GET /koa **Description**: Example handler for Koa using the @Ctx decorator. **Method**: GET **Endpoint**: /koa **Parameters**: **Request Body**: None **Response**: #### Success Response (200) - **state** (object) - The Koa context state object. #### Response Example ```json { "state": {} } ``` ``` -------------------------------- ### Create Express Server with Controllers Source: https://github.com/typestack/routing-controllers/blob/develop/docs/lang/chinese/README.md Initialize an Express server using createExpressServer, passing an array of controller classes to the 'controllers' option. The server will automatically register routes defined in these controllers. ```typescript import { createExpressServer } from 'routing-controllers'; import { UserController } from './UserController'; const app = createExpressServer({ controllers: [UserController], }); app.listen(3000); ``` -------------------------------- ### Disable Global Validation in Routing Controllers Source: https://github.com/typestack/routing-controllers/blob/develop/README.md To disable automatic validation for all parameters globally, pass `validation: false` to the `createExpressServer` options. This example shows how to disable validation when creating the Express server. ```typescript import { createExpressServer } from 'routing-controllers'; createExpressServer({ validation: false, }).listen(3000); ``` -------------------------------- ### Parameter Injection Decorators Source: https://github.com/typestack/routing-controllers/blob/develop/lang/chinese/README.md Demonstrates how to inject various types of parameters into controller methods using decorators. ```APIDOC ## Cookie Parameter Injection ### Description Inject cookie parameters using the `@CookieParam` decorator. ### Method GET ### Endpoint /users ### Parameters #### Query Parameters - **username** (string) - Required - The username from the cookie. ### Request Example ```typescript @Get("/users") getUsers(@CookieParam("username") username: string) { } ``` ## Session Object Injection ### Description Inject a session value or the entire session object using `@SessionParam` or `@Session`. ### Method GET ### Endpoint /login ### Parameters #### Request Body - **user** (User) - Required - The user object from the session. - **post** (Post) - Required - The post object from the request body. ### Request Example ```typescript @Get("/login") savePost(@SessionParam("user") user: User, @Body() post: Post) {} ``` ### Description Inject the entire session object. ### Request Example ```typescript @Get("/login") savePost(@Session() session: any, @Body() post: Post) {} ``` ### Description To make the session parameter optional, mark it as non-required. ### Request Example ```typescript action(@Session("user", { required: false }) user: User){} ``` ## State Object Injection ### Description Inject state parameters using the `@State` decorator. This feature is only supported by Koa. ### Method GET ### Endpoint /login ### Parameters #### Request Body - **user** (User) - Required - The user object from the state. - **post** (Post) - Required - The post object from the request body. ### Request Example ```typescript @Get("/login") savePost(@State("user") user: User, @Body() post: Post){} ``` ### Description To inject the entire state object, use the `@State()` decorator without arguments. ## Uploaded File Injection ### Description Inject uploaded files using the `@UploadedFile` or `@UploadFiles` decorators. Routing-controllers uses `multer` for file uploads. ### Method POST ### Endpoint /files ### Parameters #### Request Body - **fileName** (any) - Required - The uploaded file. ### Request Example ```typescript @Post("/files") saveFile(@UploadFile("fileName") file: any) {} ``` ### Description Customize multer upload options by providing an `options` object to the decorator. ### Request Example ```typescript // For cleaner code, extract this function to a separate file export const fileUploadOptions = () => { storage: multer.diskStorage({ destination: (req: any, file: any, cb: any) => { ... }, filename: (req: any, file: any, cb: any) => { ... } }), fileFilter: (req: any, file: any, cb: any) => { ... }, limits: { fieldNameSize: 255, fileSize: 1024 * 1024 * 2 } }; // Configure the decorator @Post("/files") saveFile(@UploadedFile("fileName", { options: fileUploadOptions }) file: any) {} ``` ### Description Use `@UploadFiles` to inject all uploaded files. ### Description If `multer` type declarations are installed, use `files: File[]` instead of `any[]`. ``` -------------------------------- ### Rendering HTML Templates with @Render Source: https://context7.com/typestack/routing-controllers/llms.txt Use the @Render decorator to specify an HTML template for a route. The returned object's properties become template variables. Ensure the template engine is configured in your server setup. ```typescript import { Controller, Get, Render, Param } from 'routing-controllers'; @Controller('/pages') export class PageController { @Get('/') @Render('index.html') homePage() { return { title: 'Welcome', message: 'Hello World', items: ['Item 1', 'Item 2', 'Item 3'] }; } @Get('/users/:id') @Render('user-profile.html') userProfile(@Param('id') id: number) { return { user: { id, name: 'John Doe', email: 'john@example.com' }, pageTitle: 'User Profile' }; } @Get('/dashboard') @Render('dashboard.html') dashboard() { return { stats: { users: 150, orders: 45, revenue: 12500 }, recentActivity: [ { action: 'User signup', time: '2 mins ago' }, { action: 'Order placed', time: '5 mins ago' } ] }; } } // GET /pages/ -> Renders index.html with provided variables // GET /pages/users/1 -> Renders user-profile.html with user data // GET /pages/dashboard -> Renders dashboard.html with stats ``` -------------------------------- ### Initialize Server with Global Middleware Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Configure the Express server to use global middlewares during initialization. List the middleware classes in the 'middlewares' array. ```typescript import { createExpressServer } from 'routing-controllers'; import { UserController } from './UserController'; import { LoggingMiddleware } from './LoggingMiddleware'; createExpressServer({ controllers: [UserController], middlewares: [LoggingMiddleware], }).listen(3000); ``` -------------------------------- ### Custom Headers and Rendering Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Details on setting custom response headers and rendering templates. ```APIDOC ## GET /users/:id ### Description This endpoint retrieves a user by ID and sets a custom `Cache-Control` header to `none`. ### Method GET ### Endpoint /users/:id ### Parameters #### Path Parameters - **id** (number) - Required - The ID of the user to retrieve. ### Response #### Success Response (200) - **Cache-Control** header is set to `none`. - **(response body)** - Details of the user. #### Response Example ```json { "example": "{\"id\": 1, \"name\": \"Alice\"}" } ``` ``` ```APIDOC ## GET /users/:id ### Description This endpoint retrieves a user by ID and renders an `index.html` template. The returned object provides data to be used within the template. ### Method GET ### Endpoint /users/:id ### Parameters #### Path Parameters - **id** (number) - Required - The ID of the user to retrieve. ### Request Example ```json { "example": "(No request body for this example)" } ``` ### Response #### Success Response (200) - Renders the `index.html` template with the provided data. #### Response Example ```html
Param1: these params are used
Param2: in templating engine
``` ``` -------------------------------- ### createKoaServer Source: https://context7.com/typestack/routing-controllers/llms.txt Creates and configures a Koa.js application with routing-controllers, automatically loading controllers, middlewares, and interceptors. ```APIDOC ## createKoaServer ### Description Creates and configures a Koa.js application with all registered controllers, middlewares, and interceptors automatically loaded and routes registered based on decorator metadata. ### Method `createKoaServer` function ### Endpoint N/A (This function creates the server instance) ### Parameters - `options` (object) - Required - Configuration options for the server. - `controllers` (array) - Required - An array of controller classes. - `routePrefix` (string) - Optional - A prefix for all routes. - `cors` (boolean or object) - Optional - Enable CORS. - `validation` (boolean) - Optional - Enable request body validation. ### Request Example ```typescript import 'reflect-metadata'; import { createKoaServer } from 'routing-controllers'; import { UserController } from './controllers/UserController'; const app = createKoaServer({ controllers: [UserController], routePrefix: '/api', cors: true, validation: true }); app.listen(3000, () => { console.log('Koa server running on http://localhost:3000'); }); ``` ### Response - `Koa.Application` - The configured Koa application instance. ### Response Example ``` // Koa server starts with all controller routes registered // GET http://localhost:3000/api/users -> returns all users ``` ``` -------------------------------- ### Define HTTP Route Handlers with Method Decorators Source: https://context7.com/typestack/routing-controllers/llms.txt Use HTTP method decorators like @Get, @Post, @Put, @Patch, @Delete, @Head, and @All to register controller methods as route handlers. These decorators accept an optional route path that supports Express-style parameters. ```typescript import { Controller, Get, Post, Put, Patch, Delete, Head, All, Param, Body } from 'routing-controllers'; @Controller('/resources') export class ResourceController { @Get() list() { return ['resource1', 'resource2']; } @Get('/:id') findOne(@Param('id') id: string) { return { id, name: 'Resource' }; } @Post() create(@Body() data: any) { return { created: true, data }; } @Put('/:id') replace(@Param('id') id: string, @Body() data: any) { return { replaced: true, id, data }; } @Patch('/:id') update(@Param('id') id: string, @Body() data: any) { return { updated: true, id, data }; } @Delete('/:id') remove(@Param('id') id: string) { return { deleted: true, id }; } @Head('/:id') checkExists(@Param('id') id: string) { // Returns only headers, no body return; } @All('/webhook') handleWebhook() { return { received: true }; } } // All standard HTTP methods are supported // @All matches any HTTP method ``` -------------------------------- ### Create a Middleware Class Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Implement the ExpressMiddlewareInterface to create a middleware class. The 'use' method contains the middleware logic. ```typescript import { ExpressMiddlewareInterface } from 'routing-controllers'; export class MyMiddleware implements ExpressMiddlewareInterface { // interface implementation is optional use(request: any, response: any, next?: (err?: any) => any): any { console.log('do something...'); next(); } } ``` -------------------------------- ### Protecting Routes with @Authorized Decorator Source: https://context7.com/typestack/routing-controllers/llms.txt Use the @Authorized decorator to protect controller actions. It works with a custom authorizationChecker function defined in server options to verify user credentials and roles. Examples show protecting all actions in a controller or specific actions with different role requirements. ```typescript import { createExpressServer, JsonController, Get, Post, Authorized, Action, Body } from 'routing-controllers'; // Server setup with authorization checker const app = createExpressServer({ controllers: [AdminController, UserController], authorizationChecker: async (action: Action, roles: string[]) => { const token = action.request.headers['authorization']; if (!token) return false; // Simulate user lookup const user = { id: 1, roles: ['user', 'admin'] }; // No specific roles required - just needs to be authenticated if (!roles.length) return true; // Check if user has required role return roles.some(role => user.roles.includes(role)); } }); @JsonController('/admin') export class AdminController { // Requires authentication @Authorized() @Get('/dashboard') getDashboard() { return { adminData: true }; } // Requires specific role @Authorized('admin') @Post('/users') createUser(@Body() user: any) { return { created: true, user }; } // Requires any of multiple roles @Authorized(['admin', 'moderator']) @Get('/reports') getReports() { return { reports: [] }; } } @JsonController('/profile') @Authorized() // All actions in controller require auth export class UserController { @Get() getProfile() { return { name: 'John Doe' }; } } ``` ```text GET /admin/dashboard without token -> 401 Unauthorized GET /admin/dashboard with valid token -> { adminData: true } POST /admin/users without admin role -> 403 Forbidden ``` -------------------------------- ### Loading Middlewares and Controllers from Directories Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Automatically loads middleware and controller files from specified directories. This simplifies project structure and organization. ```typescript import express from "express"; import { useExpressServer } from "routing-controllers"; const app = express(); useExpressServer(app, { controllers: [__dirname + "/controllers/**/*.ts"], middlewares: [__dirname + "/middleware/**/*.ts"], }); app.listen(3000, () => { console.log("Server listening on port 3000"); }); ``` -------------------------------- ### Apply Middleware with @UseBefore and @UseAfter Source: https://context7.com/typestack/routing-controllers/llms.txt Use @UseBefore to run middleware before an action or controller, and @UseAfter to run it after. Custom middleware must implement ExpressMiddlewareInterface. Ensure necessary imports are present. ```typescript import { Controller, Get, Post, UseBefore, UseAfter, ExpressMiddlewareInterface } from 'routing-controllers'; import { Request, Response, NextFunction } from 'express'; import compression from 'compression'; // Custom middleware class class AuthMiddleware implements ExpressMiddlewareInterface { use(request: Request, response: Response, next: NextFunction): void { const token = request.headers.authorization; if (!token) { return response.status(401).json({ error: 'Unauthorized' }); } (request as any).user = { id: 1, name: 'John' }; next(); } } class AuditLogMiddleware implements ExpressMiddlewareInterface { use(request: Request, response: Response, next: NextFunction): void { console.log(`Action completed: ${request.method} ${request.url}`); next(); } } // Controller-level middleware @Controller('/admin') @UseBefore(AuthMiddleware) export class AdminController { @Get('/dashboard') dashboard() { return { admin: true }; } // Action-level additional middleware @Post('/sensitive') @UseBefore(AuditLogMiddleware) @UseAfter(AuditLogMiddleware) sensitiveAction() { return { performed: true }; } } // Using existing Express middleware @Controller('/api') @UseBefore(compression()) export class ApiController { @Get('/data') getData() { return { large: 'data'.repeat(1000) }; } } // AuthMiddleware runs before all AdminController actions // AuditLogMiddleware runs before and after sensitiveAction ``` -------------------------------- ### Inject Query Parameters Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Demonstrates how to inject query parameters using the @QueryParam decorator. It also shows how to handle array parameters with `isArray: true` and specify types with the `type` option. ```APIDOC ## GET /users ### Description Retrieves a list of users with an optional limit. ### Method GET ### Endpoint /users #### Query Parameters - **limit** (number) - Optional - The maximum number of users to return. ### Request Example GET /users?limit=10 ### Response #### Success Response (200) - **users** (array) - A list of user objects. ## GET /users/by-multiple-ids ### Description Retrieves users by multiple IDs. ### Method GET ### Endpoint /users/by-multiple-ids #### Query Parameters - **ids** (string[]) - Optional - An array of user IDs. - **ids** (number[]) - Optional - An array of user IDs, cast to numbers. ### Request Example GET /users/by-multiple-ids?ids=a&ids=b GET /users/by-multiple-ids?ids=1&ids=3.5 ### Response #### Success Response (200) - **users** (array) - A list of user objects. ## GET /users ### Description Retrieves a list of users with advanced filtering options. ### Method GET ### Endpoint /users #### Query Parameters - **limit** (number) - Required - The maximum number of users to return. - **city** (string) - Required - The city to filter users by. - **role** (Roles) - Required - The role of the users to filter by (Admin, User, Guest). - **isActive** (boolean) - Required - Whether the users should be active. - **ids** (number[]) - Required - An array of user IDs. ### Request Example GET /users?limit=10&city=NewYork&role=admin&isActive=true&ids=1&ids=2 ### Response #### Success Response (200) - **users** (array) - A list of user objects matching the query criteria. ``` -------------------------------- ### Default Settings Configuration Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Allows setting default options for routing-controllers, such as `routePrefix`, `controllers`, `middlewares`, etc., when initializing the server. ```typescript import express from "express"; import { useExpressServer } from "routing-controllers"; const app = express(); useExpressServer(app, { routePrefix: "/api", controllers: [__dirname + "/controllers/*.js"], defaultErrorHandler: false, // Example: disable default error handler }); app.listen(3000, () => { console.log("Server listening on port 3000"); }); ``` -------------------------------- ### Using Request and Response Objects Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Demonstrates accessing the underlying Express or Koa request and response objects within a controller action. Import `Res` and `Req` decorators. ```typescript import { JsonController, Get, Req, Res } from "routing-controllers"; import * as express from "express"; @JsonController() export class UserController { @Get("/users") getAll(@Req() req: express.Request, @Res() res: express.Response) { console.log(req.accepts('json')); return res.send("Hello from Express!"); } } ``` -------------------------------- ### Using InversifyAdapter with routing-controllers Source: https://github.com/typestack/routing-controllers/blob/develop/README.md Configure routing-controllers to use a custom InversifyJS IoC adapter during application startup. ```typescript // Somewhere in your app startup import { useContainer } from 'routing-controllers'; import { Container } from 'inversify'; import { InversifyAdapter } from './inversify-adapter.ts'; const container = new Container(); const inversifyAdapter = new InversifyAdapter(container); useContainer(inversifyAdapter); ```