routing-controllers
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
- Example of usage
- More examples
- Working with json
- Return promises
- Using Request and Response objects
- Pre-configure express/koa
- Load all controllers from the given directory
- Prefix all controllers routes
- Prefix controller with base route
- Inject routing parameters
- Inject query parameters
- Inject request body
- Inject request body parameters
- Inject request header parameters
- Inject cookie parameters
- Inject session object
- Inject state object
- Inject uploaded file
- Make parameter required
- Convert parameters to objects
- Set custom ContentType
- Set Location
- Set Redirect
- Set custom HTTP code
- Controlling empty responses
- Set custom headers
- Render templates
- Throw HTTP errors
- Enable CORS
- Default settings
- Using middlewares
- Using interceptors
- Creating instances of classes from action params
- Auto validating action params
- Using authorization features
- Using DI container
- Custom parameter decorators
- Decorators Reference
- Samples
- Release notes
Installation
-
Install module:
npm install routing-controllers --save
-
reflect-metadata
shim is required:npm install reflect-metadata --save
and make sure to import it before you use routing-controllers:
; -
Install framework:
a. If you want to use routing-controllers with express.js, then install it and all required dependencies:
npm install express body-parser multer --save
Optionally you can also install their typings:
npm install @types/express @types/body-parser @types/multer --save
b. If you want to use routing-controllers with koa 2, then install it and all required dependencies:
npm install koa koa-router koa-bodyparser koa-multer --save
Optionally you can also install their typings:
npm install @types/koa @types/koa-router @types/koa-bodyparser --save
-
Its important to set these options in
tsconfig.json
file of your project:
Example of usage
-
Create a file
UserController.ts
;@@{return "This action returns all users";}@return "This action returns user #" + id;@return "Saving user...";@return "Updating a user...";@return "Removing user...";This class will register routes specified in method decorators in your server framework (express.js or koa).
-
Create a file
app.ts
; // this shim is required;;// creates express app, registers all controller routes and returns you express app instanceconst app =;// run express application on port 3000app;if you are koa user you just need to use
createKoaServer
instead ofcreateExpressServer
-
Open in browser
http://localhost:3000/users
. You will seeThis action returns all users
in your browser. If you openhttp://localhost:3000/users/1
you will seeThis action returns user #1
.
More examples
Working with json
If you are designing a REST API where your endpoints always receive and return JSON then
you can use @JsonController
decorator instead of @Controller
.
This will guarantee you that data returned by your controller actions always be transformed to JSON
and Content-Type
header will be always set to application/json
.
It will also guarantee application/json
header is understood from the requests and the body parsed as JSON:
; @ @ { return userRepository; } @ return userRepository; @ return userRepository;
Return promises
You can return a promise in the controller, and it will wait until promise resolved and return promise result in a response body.
; @ @ { return userRepository; } @ return userRepository; @ return userRepository; @ return userRepository; @ return userRepository;
Using Request and Response objects
You 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.
; @ @ return response;
@Req()
decorator injects you a Request
object, and @Res()
decorator injects you a Response
object.
If you have installed typings, you can use their types:
;; @ @ return response;
note: koa users can also use
@Ctx() context
to inject koa's Context object.
Pre-configure express/koa
If you have, or if you want to create and configure express app separately,
you can use useExpressServer
instead of createExpressServer
function:
;; let express = ; // or you can import it if you have installed typingslet app = ; // your created express server// app.use() // you can configure it the way you want;app; // run your express server
koa users must use
useKoaServer
instead ofuseExpressServer
Load all controllers from the given directory
You can load all controllers from directories, by specifying array of directories in options of
createExpressServer
or useExpressServer
:
;; ; // register controllers routes in our express application
koa users must use
createKoaServer
instead ofcreateExpressServer
Prefix all controllers routes
If you want to prefix all your routes, e.g. /api
you can use routePrefix
option:
;;; ;
koa users must use
createKoaServer
instead ofcreateExpressServer
Prefix controller with base route
You can prefix all specific controller's actions with base route:
@ // ...
Inject routing parameters
You can use @Param
decorator to inject parameters in your controller actions:
@ // id will be automatically casted to "number" because it has type number
If you want to inject all parameters use @Params()
decorator.
Inject query parameters
To inject query parameters, use @QueryParam
decorator:
@
If you want to inject all query parameters use @QueryParams()
decorator.
Inject request body
To inject request body, use @Body
decorator:
@
If you specify a class type to parameter that is decorated with @Body()
,
routing-controllers will use class-transformer to create instance of the given class type from the data received in request body.
To disable this behaviour you need to specify a { classTransformer: false }
in RoutingControllerOptions when creating a server.
Inject request body parameters
To inject request body parameter, use @BodyParam
decorator:
@
Inject request header parameters
To inject request header parameter, use @HeaderParam
decorator:
@
If you want to inject all header parameters use @HeaderParams()
decorator.
Inject cookie parameters
To get a cookie parameter, use @CookieParam
decorator:
@
If you want to inject all header parameters use @CookieParams()
decorator.
Inject session object
To inject a session value, use @Session
decorator:
@
If you want to inject the main session object, use @Session()
without any parameters.
The parameter marked with @Session
decorator is required by default. If your action param is optional, you have to mark it as not required:
action@Session"user", user: User
Express uses express-session / Koa uses koa-session or koa-generic-session to handle session, so firstly you have to install it manually to use @Session
decorator.
Inject state object
To inject a state parameter use @State
decorator:
@
If you want to inject the whole state object use @State()
without any parameters.
This feature is only supported by Koa.
Inject uploaded file
To inject uploaded file, use @UploadedFile
decorator:
@
You can also specify uploading options to multer this way:
// to keep code clean better to extract this function into separate fileconst fileUploadOptions = { storage: multer { ... } limits: fieldNameSize: 255 fileSize: 1024 * 1024 * 2 }; // use options this way:@
To inject all uploaded files use @UploadedFiles
decorator instead.
Routing-controllers uses multer to handle file uploads.
You can install multer's file definitions via typings, and use files: File[]
type instead of any[]
.
Make parameter required
To make any parameter required, simply pass a required: true
flag in its options:
@ // your method will not be executed if user is not sent in a request
Same you can do with all other parameters @QueryParam
, @BodyParam
and others.
If user request does not contain required parameter routing-controller will throw an error.
Convert parameters to objects
If you specify a class type to parameter that is decorated with parameter decorator, routing-controllers will use class-transformer to create instance of that class type. More info about this feature is available here.
Set custom ContentType
You can specify a custom ContentType header:
@@ { // ...}
Set Location
You can set a Location header for any action:
@@Location"http://github.com" { // ...}
Set Redirect
You can set a Redirect header for any action:
@@ { // ...}
You can override the Redirect header by returning a string value:
getUsers
You can use template to generate the Redirect header:
getUsers
Set custom HTTP code
You can explicitly set a returned HTTP code for any action:
@@ // ...
Controlling empty responses
If your controller returns void
or Promise<void>
or undefined
it will throw you 404 error.
To prevent this if you need to specify what status code you want to return using @OnUndefined
decorator.
@@async : Promise<void> return userRepository;
@OnUndefined
is also useful when you return some object which can or cannot be undefined.
In this example findOneById
returns undefined in the case if user with given id was not found.
This action will return 404 in the case if user was not found, and regular 200 in the case if it was found.
@@ return userRepository;
You can also specify error class you want to use if it returned undefined:
; { super404 "User not found!"; }
@@ return userRepository;
If controller action returns null
you can use @OnNull
decorator instead.
Set custom headers
You can set any custom header in a response:
@@ // ...
Render templates
If you are using server-side rendering you can render any template:
@@ { return param1: "these params are used" param2: "in templating engine" ;}
To use rendering ability make sure to configure express / koa properly. To use rendering ability with Koa you will need to use a rendering 3rd party such as koa-views, koa-views is the only render middleware that has been tested.
Throw HTTP errors
If you want to return errors with specific error codes, there is an easy way:
@ const user = thisuserRepository; if !user throw `User was not found.`; // message is optional return user;
Now, when user won't be found with requested id, response will be with http status code 404 and following content:
There are set of prepared errors you can use:
- HttpError
- BadRequestError
- ForbiddenError
- InternalServerError
- MethodNotAllowedError
- NotAcceptableError
- NotFoundError
- UnauthorizedError
You can also create and use your own errors by extending HttpError
class.
To define the data returned to the client, you could define a toJSON method in your error.
public operationName: string; public args: any; { super500; Object; thisoperationName = operationName; thisargs = args; // can be used for internal logging } { return status: thishttpCode failedOperation: thisoperationName }
Enable CORS
Since CORS is a future that is used almost in any web-api application, you can enable it in routing-controllers options.
;;; const app = ; app;
To use cors you need to install its module.
For express its npm i cors
, for koa its npm i kcors
.
You can pass cors options as well:
;;; const app = ; app;
Default settings
You can override default status code in routing-controllers options.
;;; const app = ; app;
Using middlewares
You can use any existing express / koa middleware, or create your own.
To create your middlewares there is a @Middleware
decorator,
and to use already exist middlewares there are @UseBefore
and @UseAfter
decorators.
Use existing middleware
There are multiple ways to use middleware. For example, lets try to use compression middleware:
-
Install compression middleware:
npm install compression
-
To use middleware per-action:
;let compression = ;// ...@@// ...This way compression middleware will be applied only for
getOne
controller action, and will be executed before action execution. To execute middleware after action use@UseAfter
decorator instead. -
To use middleware per-controller:
;let compression = ;@@This way compression middleware will be applied for all actions of the
UserController
controller, and will be executed before its action execution. Same way you can use@UseAfter
decorator here. -
If you want to use compression module globally for all controllers you can simply register it during bootstrap:
;;; // we need to "load" our controller before call createExpressServer. this is requiredlet compression = ;let app =; // creates express app, registers all controller routes and returns you express app instanceapp;app; // run express applicationAlternatively, you can create a custom global middleware and simply delegate its execution to the compression module.
Creating your own express middleware
Here is example of creating middleware for express.js:
-
There are two ways of creating middleware:
First, you can create a simple middleware function:
: any {console;;}Second you can create a class:
;implements ExpressMiddlewareInterface // interface implementation is optional: anyconsole;;Then you can use them this way:
;;;@@@or per-action:
@@@// ...@UseBefore
executes middleware before controller action.@UseAfter
executes middleware after each controller action.
Creating your own koa middleware
Here is example of creating middleware for koa.js:
-
There are two ways of creating middleware:
First, you can create a simple middleware function:
: Promise<any> {console;return;}Second you can create a class:
;implements KoaMiddlewareInterface // interface implementation is optional: Promise<any>console;return;Then you can them this way:
;;;@@@or per-action:
@@@// ...@UseBefore
executes middleware before controller action.@UseAfter
executes middleware after each controller action.
Global middlewares
Global middlewares run before each request, always.
To make your middleware global mark it with @Middleware
decorator and specify if it runs after or before controllers actions.
; @ implements ExpressMiddlewareInterface : void console; ;
To enable this middleware, specify it during routing-controllers initialization:
;;;; ;
Error handlers
Error handlers are specific only to express.
Error handlers work same way as middlewares, but implement ExpressErrorMiddlewareInterface
:
-
Create a class that implements the
ErrorMiddlewareInterface
interface:;@implements ExpressErrorMiddlewareInterfaceconsole;;
Custom error handlers are invoked after the default error handler, so you won't be able to change response code or headers.
To prevent this, you have to disable default error handler by specifying defaultErrorHandler
option in createExpressServer or useExpressServer:
;
Loading middlewares, interceptors and controllers from directories
Also you can load middlewares from directories. Also you can use glob patterns:
;;;
Using interceptors
Interceptors are used to change or replace the data returned to the client. You can create your own interceptor class or function and use to all or specific controller or controller action. It works pretty much the same as middlewares.
Interceptor function
The easiest way is to use functions directly passed to @UseInterceptor
of the action.
; // ... @@ return "Hello, I am Mike!"; // client will get a "Hello, I am Michael!" response.
You can use @UseInterceptor
per-action, on per-controller.
If its used per-controller then interceptor will apply to all controller actions.
Interceptor classes
You can also create a class and use it with @UseInterceptor
decorator:
; implements InterceptorInterface { return content; }
And use it in your controllers this way:
;; // ... @@ return "Hello, I am Mike!"; // client will get a "Hello, I am Michael!" response.
Global interceptors
You can create interceptors that will affect all controllers in your project by creating interceptor class
and mark it with @Interceptor
decorator:
; @ implements InterceptorInterface { return content; }
Creating instances of classes from action params
When user sends a json object and you are parsing it, sometimes you want to parse it into object of some class, instead of parsing it into simple literal object.
You have ability to do this using class-transformer.
To use it simply specify a classTransformer: true
option on application bootstrap:
;; ;
Now, when you parse your action params, if you have specified a class, routing-controllers will create you a class of that instance with the data sent by a user:
firstName: string; lastName: string; : string return thislastName + " " + thisfirstName; @ console;
If User
is an interface - then simple literal object will be created.
If its a class - then instance of this class will be created.
This technique works with @Body
, @Param
, @QueryParam
, @BodyParam
, and other decorators.
Learn more about class-transformer and how to handle more complex object constructions here.
This behaviour is enabled by default.
If you want to disable it simply pass classTransformer: false
to createExpressServer method.
Auto validating action params
Sometimes parsing a json object into instance of some class is not enough.
E.g. class-transformer
doesn't check whether the property's types are correct, so you can get runtime error if you rely on TypeScript type safe. Also you may want to validate the object to check e.g. whether the password string is long enough or entered e-mail is correct.
It can be done easily thanks to integration with class-validator. This behaviour is enabled by default. If you want to disable it, you need to do it explicitly e.g. by passing validation: false
option on application bootstrap:
;; ;
If you want to turn on the validation only for some params, not globally for every parameter, you can do this locally by setting validate: true
option in parameter decorator options object:
@
Now you need to define the class which type will be used as type of controller's method param. Decorate the properties with appropriate validation decorators.
@ email: string; @ password: string;
If you haven't used class-validator yet, you can learn how to use the decorators and handle more complex object validation here.
Now, if you have specified a class type, your action params will be not only an instance of that class (with the data sent by a user) but they will be validated too, so you don't have to worry about eg. incorrect e-mail or too short password and manual checks every property in controller method body.
@ @ console; console;
If the param doesn't satisfy the requirements defined by class-validator decorators, an error will be thrown and captured by routing-controller, so the client will receive 400 Bad Request and JSON with nice detailed Validation errors array.
If you need special options for validation (groups, skipping missing properties, etc.) or transforming (groups, excluding prefixes, versions, etc.), you can pass them as global config as validation
in createExpressServer method or as a local validate
setting for method parameter - @Body({ validate: localOptions })
.
This technique works not only with @Body
but also with @Param
, @QueryParam
, @BodyParam
and other decorators.
Using authorization features
Routing-controllers comes with two decorators helping you to organize authorization in your application.
@Authorized
decorator
To make @Authorized
decorator to work you need to setup special routing controllers options:
;; ;
You can use @Authorized
on controller actions:
@ @ @ @ // you can specify roles or array of roles @
@CurrentUser
decorator
To make @CurrentUser
decorator to work you need to setup special routing controllers options:
;; ;
You can use @CurrentUser
on controller actions:
@ @ @
If you mark @CurrentUser
as required
and currentUserChecker logic will return empty result,
then routing-controllers will throw authorization required error.
Using DI container
routing-controllers
supports a DI container out of the box. You can inject your services into your controllers,
middlewares and error handlers. Container must be setup during application bootstrap.
Here is example how to integrate routing-controllers with typedi:
;;; // its important to set container before any operation you do with routing-controllers,// including importing controllers; // create and run server;
That's it, now you can inject your services into your controllers:
@ { } // ... controller actions
Custom parameter decorators
You can create your own parameter decorators. Here is simple example how "session user" can be implemented using custom decorators:
; { return ;}
And use it in your controller:
@ @ // here you'll have user authorized and you can safely save your question // in the case if user returned your undefined from the database and "required" // parameter was set, routing-controllers will throw you ParameterRequired error
Decorators Reference
Controller Decorators
Signature | Example | Description |
---|---|---|
@Controller(baseRoute: string) |
@Controller("/users") class SomeController |
Class that is marked with this decorator is registered as controller and its annotated methods are registered as actions. Base route is used to concatenate it to all controller action routes. |
@JsonController(baseRoute: string) |
@JsonController("/users") class SomeJsonController |
Class that is marked with this decorator is registered as controller and its annotated methods are registered as actions. Difference between @JsonController and @Controller is that @JsonController automatically converts results returned by controller to json objects (using JSON.parse) and response being sent to a client is sent with application/json content-type. Base route is used to concatenate it to all controller action routes. |
Controller Action Decorators
Signature | Example | Description | express.js analogue |
---|---|---|---|
@Get(route: string\|RegExp) |
@Get("/users") all() |
Methods marked with this decorator will register a request made with GET HTTP Method to a given route. In action options you can specify if action should response json or regular text response. | app.get("/users", all) |
@Post(route: string\|RegExp) |
@Post("/users") save() |
Methods marked with this decorator will register a request made with POST HTTP Method to a given route. In action options you can specify if action should response json or regular text response. | app.post("/users", save) |
@Put(route: string\|RegExp) |
@Put("/users/:id") update() |
Methods marked with this decorator will register a request made with PUT HTTP Method to a given route. In action options you can specify if action should response json or regular text response. | app.put("/users", update) |
@Patch(route: string\|RegExp) |
@Patch("/users/:id") patch() |
Methods marked with this decorator will register a request made with PATCH HTTP Method to a given route. In action options you can specify if action should response json or regular text response. | app.patch("/users/:id", patch) |
@Delete(route: string\|RegExp) |
@Delete("/users/:id") delete() |
Methods marked with this decorator will register a request made with DELETE HTTP Method to a given route. In action options you can specify if action should response json or regular text response. | app.delete("/users/:id", delete) |
@Head(route: string\|RegExp) |
@Head("/users/:id") head() |
Methods marked with this decorator will register a request made with HEAD HTTP Method to a given route. In action options you can specify if action should response json or regular text response. | app.head("/users/:id", head) |
@Method(methodName: string, route: string\|RegExp) |
@Method("move", "/users/:id") move() |
Methods marked with this decorator will register a request made with given methodName HTTP Method to a given route. In action options you can specify if action should response json or regular text response. |
app.move("/users/:id", move) |
Method Parameter Decorators
Signature | Example | Description | express.js analogue |
---|---|---|---|
@Req() |
getAll(@Req() request: Request) |
Injects a Request object. | function (request, response) |
@Res() |
getAll(@Res() response: Response) |
Injects a Response object. | function (request, response) |
@Ctx() |
getAll(@Ctx() context: Context) |
Injects a Context object (koa-specific) | function (ctx) (koa-analogue) |
@Param(name: string, options?: ParamOptions) |
get(@Param("id") id: number) |
Injects a router parameter. | request.params.id |
@Params() |
get(@Params() params: any) |
Injects all request parameters. | request.params |
@QueryParam(name: string, options?: ParamOptions) |
get(@QueryParam("id") id: number) |
Injects a query string parameter. | request.query.id |
@QueryParams() |
get(@QueryParams() params: any) |
Injects all query parameters. | request.query |
@HeaderParam(name: string, options?: ParamOptions) |
get(@HeaderParam("token") token: string) |
Injects a specific request headers. | request.headers.token |
@HeaderParams() |
get(@HeaderParams() params: any) |
Injects all request headers. | request.headers |
@CookieParam(name: string, options?: ParamOptions) |
get(@CookieParam("username") username: string) |
Injects a cookie parameter. | request.cookie("username") |
@CookieParams() |
get(@CookieParams() params: any) |
Injects all cookies. | `request.cookies |
@Session(name?: string) |
get(@Session("user") user: User) |
Injects an object from session (or the whole session). | request.session.user |
@State(name?: string) |
get(@State() session: StateType) |
Injects an object from the state (or the whole state). | ctx.state (koa-analogue) |
@Body(options?: BodyOptions) |
post(@Body() body: any) |
Injects a body. In parameter options you can specify body parser middleware options. | request.body |
@BodyParam(name: string, options?: ParamOptions) |
post(@BodyParam("name") name: string) |
Injects a body parameter. | request.body.name |
@UploadedFile(name: string, options?: UploadOptions) |
post(@UploadedFile("filename") file: any) |
Injects uploaded file from the response. In parameter options you can specify underlying uploader middleware options. | request.file.file (using multer) |
@UploadedFiles(name: string, options?: UploadOptions) |
post(@UploadedFiles("filename") files: any[]) |
Injects all uploaded files from the response. In parameter options you can specify underlying uploader middleware options. | request.files (using multer) |
Middleware and Interceptor Decorators
Signature | Example | Description |
---|---|---|
@Middleware({ type: "before"\|"after" }) |
@Middleware({ type: "before" }) class SomeMiddleware |
Registers a global middleware. |
@UseBefore() |
@UseBefore(CompressionMiddleware) |
Uses given middleware before action is being executed. |
@UseAfter() |
@UseAfter(CompressionMiddleware) |
Uses given middleware after action is being executed. |
@Interceptor() |
@Interceptor() class SomeInterceptor |
Registers a global interceptor. |
@UseInterceptor() |
@UseInterceptor(BadWordsInterceptor) |
Intercepts result of the given controller/action and replaces some values of it. |
Other Decorators
Signature | Example | Description |
---|---|---|
@Authorized(roles?: string\|string[]) |
@Authorized("SUPER_ADMIN") get() |
Checks if user is authorized and has given roles on a given route. currentUserChecker should be defined in routing-controllers options. |
@CurrentUser(options?: { required?: boolean }) |
get(@CurrentUser({ required: true }) user: User) | Injects currently authorized user. currentUserChecker should be defined in routing-controllers options. |
@Header(contentType: string) |
@Header("Cache-Control", "private") get() |
Allows to explicitly set any HTTP header returned in the response. |
@ContentType(contentType: string) |
@ContentType("text/csv") get() |
Allows to explicitly set HTTP Content-Type returned in the response. |
@Location(url: string) |
@Location("http://github.com") get() |
Allows to explicitly set HTTP Location header returned in the response. |
@Redirect(url: string) |
@Redirect("http://github.com") get() |
Allows to explicitly set HTTP Redirect header returned in the response. |
@HttpCode(code: number) |
@HttpCode(201) post() |
Allows to explicitly set HTTP code to be returned in the response. |
@OnNull(codeOrError: number\|Error) |
@OnNull(201) post() |
Sets a given HTTP code when controller action returned null. |
@OnUndefined(codeOrError: number\|Error) |
@OnUndefined(201) post() |
Sets a given HTTP code when controller action returned undefined. |
@ResponseClassTransformOptions(options: ClassTransformOptions) |
@ResponseClassTransformOptions({/*...*/}) get() |
Sets options to be passed to class-transformer when it used for classToPlain a response result. |
@Render(template: string) |
@Render("user-list.html") get() |
Renders a given html template. Data returned by a controller serve as template variables. |
Samples
- Take a look on routing-controllers with express which is using routing-controllers.
- Take a look on routing-controllers with koa which is using routing-controllers.
- Take a look on routing-controllers with angular 2 which is using routing-controllers.
- Take a look on node-microservice-demo which is using routing-controllers.
- Take a look on samples in ./sample for more examples of usage.
Release notes
See information about breaking changes and release notes here.