在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:typestack/routing-controllers开源软件地址:https://github.com/typestack/routing-controllers开源编程语言:TypeScript 99.9%开源软件介绍:routing-controllersEnglish | 中文 Allows to create controller classes with methods as actions that handle requests. You can use routing-controllers with express.js or koa.js. Table of Contents
Installation
import 'reflect-metadata';
In prior versions, these were direct dependencies, but now they are peer dependencies so you can choose when to upgrade and accept breaking changes.
Example of usage
More examplesWorking with jsonIf you are designing a REST API where your endpoints always receive and return JSON then
you can use 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);
}
} Return promisesYou can return a promise in the controller, and it will wait until promise resolved and return promise result in a response body. 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);
}
@Put('/users/:id')
put(@Param('id') id: number, @Body() user: User) {
return userRepository.updateById(id, user);
}
@Delete('/users/:id')
remove(@Param('id') id: number) {
return userRepository.removeById(id);
}
} Using Request and Response objectsYou can use framework's request and response objects directly. If you want to handle the response by yourself, just make sure you return the response object itself from the action. import { Controller, Req, Res, Get } from 'routing-controllers';
@Controller()
export class UserController {
@Get('/users')
getAllUsers(@Req() request: any, @Res() response: any) {
return response.send('Hello response!');
}
@Get('/posts')
getAllPosts(@Req() request: any, @Res() response: any) {
// some response functions don't return the response object,
// so it needs to be returned explicitly
response.redirect('/users');
return response;
}
}
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!');
}
}
Pre-configure express/koaIf you have, or if you want to create and configure express app separately,
you can use 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
Load all controllers from the given directoryYou can load all controllers from directories, by specifying array of directories in options of
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
Prefix all controllers routesIf you want to prefix all your routes, e.g. import { createExpressServer } from 'routing-controllers';
import { UserController } from './controller/UserController';
createExpressServer({
routePrefix: '/api',
controllers: [UserController],
}).listen(3000);
Prefix controller with base routeYou can prefix all specific controller's actions with base route: @Controller('/users')
export class UserController {
// ...
} Inject routing parametersYou can use @Get("/users/:id")
getOne(@Param("id") id: number) { // id will be automatically casted to "number" because it has type number
} If you want to inject all parameters use Inject query parametersTo inject query parameters, use @Get("/users")
getUsers(@QueryParam("limit") limit: number) {
} You can use @Get("/users/by-multiple-ids")
getUsers(@QueryParam("ids", { isArray: true}) ids: string[]) {
}
You can combine use @Get("/users/by-multiple-ids")
getUsers(@QueryParam("ids", { isArray: true, type: Number}) ids: number[]) {
}
If you want to inject all query parameters use enum Roles {
Admin = "admin",
User = "user",
Guest = "guest",
}
class GetUsersQuery {
@IsPositive()
limit: number;
@IsAlpha()
city: string;
@IsEnum(Roles)
role: Roles;
@IsBoolean()
isActive: boolean;
@IsArray()
@IsNumber(undefined, { each: true })
@Type(() => Number)
ids: number[];
}
@Get("/users")
getUsers(@QueryParams() query: GetUsersQuery) {
// here you can access query.role, query.limit
// and others valid query parameters
// query.ids will be an array, of numbers, even with one element
} Inject request bodyTo inject request body, use @Post("/users")
saveUser(@Body() user: User) {
} If you specify a class type to parameter that is decorated with Inject request body parametersTo inject request body parameter, use @Post("/users")
saveUser(@BodyParam("name") userName: string) {
} Inject request header parametersTo inject request header parameter, use @Post("/users")
saveUser(@HeaderParam("authorization") token: string) {
} If you want to inject all header parameters use Inject cookie parametersTo get a cookie parameter, use @Get("/users")
getUsers(@CookieParam("username") username: string) {
} If you want to inject all header parameters use Inject session objectTo inject a session value, use @Get("/login")
savePost(@SessionParam("user") user: User, @Body() post: Post) {} If you want to inject the main session object, use |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论