# Controllers
Controllers are responsible for handling incoming requests and returning responses to the client.
A controller is here to handle a specific request for a given HTTP verb and Route. The routing service is responsible for managing and dispatching request to the right Controller.
In order to create a basic controller, we use classes and decorators. Decorators associate classes with required metadata and enable Ts.ED to create a routing map.
# Routing
# Usage
In the following example we'll use the Controller decorator which is required to define a basic controller. We'll specify a path for the controller which will be used by the routing mechanism to create your routes.
import {Get} from "@tsed/schema";
import {Controller} from "@tsed/di";
@Controller("/calendars")
export class CalendarCtrl {
@Get()
findAll(): string {
return "This action returns all calendars";
}
}
2
3
4
5
6
7
8
9
10
The
Get
decorator before the findAll()
method tells Ts.ED to create an endpoint for this particular route path and
map every corresponding request to this handler. Since we've declared a prefix for every route (/calendars
), Ts.ED will map every GET /calendars
request to this method.
# Decorators
Ts.ED provides a decorator for each HTTP verb which can be used to handle a request:
Other decorators are provided to describe your route with OpenSpec, adding middlewares, adding some constraints or adding headers:
# Configuration
You can add your controller by adding glob pattern on mount
ServerSettings attributes or by importing manually your controller.
Here an example:
import {Configuration} from "@tsed/common";
import {CalendarCtrl} from "./controllers/CalendarCtrl";
@Configuration({
mount: {
"/rest": `./controllers/*.ts`, // using componentScan
// Using manual import
"/manual": [CalendarCtrl]
}
})
export class Server {}
2
3
4
5
6
7
8
9
10
11
# Create multiple versions of your API
As you have seen in the previous example, the mount
attribute is an object that let you provide the global endpoint for all your controllers under the controllers
folder.
You can add more configurations to mount different endpoints associated to a folder. Here is another configuration example:
import {Configuration} from "@tsed/di";
@Configuration({
mount: {
"/rest/v0": "./controllers/v0/**/*.ts",
"/rest/v1": "./controllers/v1/**/*.ts"
}
})
export class Server {}
2
3
4
5
6
7
8
9
# Async and Promise
Ts.ED works well with Promise and async
function.
Every async function has to return a Promise
.
This means that you can return a deferred value that Ts.ED will be able to resolve by itself.
Let's see an example of this:
import {Get} from "@tsed/schema";
import {Controller} from "@tsed/di";
import {PathParams} from "@tsed/platform-params";
interface Calendar {
id: string;
name: string;
}
@Controller("/calendars")
export class CalendarCtrl {
@Get("/:id")
async get(@PathParams("id") id: string): Promise<Calendar> {
return {
id,
name: "test"
};
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Observable/Stream/Buffer
Also, Ts.ED support function that return Observable
, Stream
or Buffer
.
import {PlatformResponse, Res} from "@tsed/common";
import {Get} from "@tsed/schema";
import {Controller} from "@tsed/di";
import {createReadStream, ReadStream} from "fs";
import {Observable, of} from "rxjs";
@Controller("/")
export class KindOfResponseCtrl {
@Get("/observable")
observable(): Observable<any[]> {
return of([]);
}
@Get("/stream")
stream(): ReadStream {
return createReadStream(__dirname + "/response.txt");
}
@Get("/buffer")
buffer(@Res() res: PlatformResponse): Buffer {
// Set attachment: res.attachment("filename")
// Set contentType: res.contentType("plain/text");
return Buffer.from("Hello");
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# Axios response
Sometime, you just want call another API to proxy a webservice. Axios is an excellent library to call API in Node.js and Ts.ED is able to handle Axios response to wrap it into an Express.js response.
import {Res} from "@tsed/common";
import {QueryParams} from "@tsed/platform-params";
import {Get} from "@tsed/schema";
import {Controller} from "@tsed/di";
import Axios from "axios";
import {IncomingMessage} from "http";
@Controller("/proxy")
export class ProxyCtrl {
@Get("/")
proxy(@QueryParams("path") path: string) {
return Axios.get(`https://cerevoice.s3.amazonaws.com/${path}`, {
responseType: "stream"
});
}
// is equivalent to doing that
@Get("/")
async proxy2(@Res() res: Res, @QueryParams("path") path: string): IncomingMessage {
const response = await Axios.get(`https://cerevoice.s3.amazonaws.com/${path}`, {
responseType: "stream"
});
res.set(response.headers);
res.status(response.status);
return response.data;
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# Multiple endpoints, single method
Ts.ED lets you define multiple endpoints on the same method, with the same verb like GET
or POST
, or with another
verb like this:
import {Get, Post} from "@tsed/schema";
import {Controller} from "@tsed/di";
@Controller("/calendars")
export class CalendarCtrl {
@Get("/:id")
@Get("/alias/:id")
@Post("/:id/complexAlias")
async get(): Promise<any> {
return "Return something";
}
}
2
3
4
5
6
7
8
9
10
11
12
# Routes order
Be aware that routes registration order (methods order in classes) matters.
Assume that you have a route that allows getting a calendar by its path (/calendars/:id
).
If you register another endpoint below the mentioned one, which basically returns all calendars at once (calendars),
the request will never hit the actual handler because all path parameters are optional.
See the following example:
import {PathParams} from "@tsed/platform-params";
import {Get} from "@tsed/schema";
import {Controller} from "@tsed/di";
@Controller("/calendars")
export class CalendarsController {
@Get("/:id")
findOne(@PathParams("id") id: string) {
return `This action returns a #${id} calendar`;
}
@Get()
findAll() {
// This endpoint will never get called
// because the "/calendars" request is going
// to be captured by the "/calendars/:id" route handler
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
In order to avoid such side-effects, simply move findAll()
method above findOne()
.
# Request
# Decorators
# Input parameters
Getting parameters from Express Request can be done by using the following decorators:
-
BodyParams
:
Express.request.body
-
RawBodyParams
:
Express.request.rawBody
-
PathParams
:
Express.request.params
-
RawPathParams
:
Express.request.params
without transformation and validation, -
QueryParams
:
Express.request.query
-
RawQueryParams
:
Express.request.query
without transformation and validation,
Finally, BodyParams accepts to give a ParamOptions object as parameter to change the decorator behavior:
import {Post} from "@tsed/schema";
import {BodyParams} from "@tsed/platform-params";
class MyController {
@Post()
async create(@BodyParams({expression: "user", useConverter: false}) body: T): Promise<T> {
console.log("payload", body);
return body;
}
}
2
3
4
5
6
7
8
9
10
11
TIP
Since v5.51.0+,
QueryParams
decorator accept a model to transform Express.request.query
plain object to a Class.
import {Controller, Get, QueryParams} from "@tsed/common";
import {Required, MinLength, Property} from "@tsed/schema";
class QueryParamsModel {
@Required()
@MinLength(1)
name: string;
@Property()
duration: number;
}
@Controller("/")
class QueryController {
@Get("/")
get(@QueryParams() params: QueryParamsModel, @QueryParams("locale") locale: string) {}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
WARNING
Since v6.0.0, use any
as type for a body parameter, will be translated as type Object
. It means, if you use @tsed/ajv
, the validation
will fail if you send a different type as expected in the payload.
import {BodyParams} from "@tsed/platform-params";
import {Post} from "@tsed/schema";
import {Controller} from "@tsed/di";
import {Any} from "@tsed/schema";
@Controller("/any")
export class AnyCtrl {
@Post()
updatePayload1(@BodyParams() payload: any): any {
// accept only Object
// breaking change with v5
console.log("payload", payload);
return payload;
}
@Post()
updatePayload2(@BodyParams() @Any() payload: any): any {
// accept all types
console.log("payload", payload);
return payload;
}
@Post()
updatePayload3(@BodyParams() payload: any[]): any {
// accept array of any types
console.log("payload", payload);
return payload;
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
Add Any decorator to fix the issue.
# Raw Body v6.20.0+
RawBodyParams
decorator provides you quick access to the request.rawBody
:
import {RawBodyParams} from "@tsed/platform-params";
import {Post} from "@tsed/schema";
import {Controller} from "@tsed/di";
@Controller("/calendars")
export class CalendarCtrl {
@Post()
post(@RawBodyParams() payload: Buffer): string {
return payload.toString("utf8");
}
}
2
3
4
5
6
7
8
9
10
11
WARNING
There is no performed input validation and deserialization when using the RawBodyParams !
WARNING
To use @RawBodyParams() properly, you have to remove bodyParser add on $beforeRoutesInit
.
@Configuration({
+ middlewares: [
+ bodyParser.json(),
+ bodyParser.urlencoded({extended: true})
+ ]
})
export class Server {
@Inject()
protected app: PlatformApplication;
$beforeRoutesInit() {
- this.app
- .use(bodyParser.json())
- .use(bodyParser.urlencoded({extended: true}));
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Headers
HeaderParams
decorator provides you quick access to the request.get()
:
import {HeaderParams} from "@tsed/platform-params";
import {Get} from "@tsed/schema";
import {Controller} from "@tsed/di";
@Controller("/calendars")
export class CalendarCtrl {
@Get()
get(@HeaderParams("x-token") token: string): string {
console.log("token", token);
return token;
}
}
2
3
4
5
6
7
8
9
10
11
12
13
# Session/Cookies/Locals/Context
For the session, cookies, locals or context data attached on the request, it works the same way as seen before. Use the following decorators to get the data:
# Locals
Locals is a response property used by third-party like template engine to render a page by the server. If you attach data on it, template engine will use it to render the template.
Here is an example:
import {Locals} from "@tsed/platform-params";
import {Middleware, UseBefore} from "@tsed/platform-middlewares";
import {View} from "@tsed/platform-views";
import {Get} from "@tsed/schema";
import {Controller} from "@tsed/di";
@Middleware()
class LocalsMiddleware {
use(@Locals() locals: any) {
// set some on locals
locals.user = "user";
}
}
@Controller("/")
@UseBefore(LocalsMiddleware)
class MyCtrl {
@Get("/")
@View("home.ejs") // will use locals and returned data to render the page
get(@Locals("user") user: any) {
console.log("user", user);
return {
description: "Hello world"
};
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# Context
See our dedicated page on PlatformContext for more details.
# Validation
Ts.ED support the data input validation with the decorators provided by @tsed/schema
.
Example:
import {PathParams} from "@tsed/platform-params";
import {Get} from "@tsed/schema";
import {Controller} from "@tsed/di";
import {MinLength} from "@tsed/schema";
@Controller("/calendars")
export class CalendarsController {
@Get(":id")
findOne(@PathParams("id") @MinLength(10) id: string) {
return `This action returns a #${id} calendar`;
}
}
2
3
4
5
6
7
8
9
10
11
12
WARNING
Validation require the @tsed/ajv
plugins to work.
npm install --save @tsed/ajv
Supported decorators:
# Response
# Decorators
# Status
You can change the default response status with the Status decorator:
import {BodyParams} from "@tsed/platform-params";
import {Returns, Put} from "@tsed/schema";
import {Controller} from "@tsed/di";
interface Calendar {
id: string;
name: string;
}
@Controller("/calendars")
export class CalendarCtrl {
@Put("/")
@Returns(201)
create(@BodyParams("name") id: string): Calendar {
return {id: "2", name: "test"};
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Content Type
You can set the response content type with the ContentType decorator:
import {BodyParams} from "@tsed/platform-params";
import {ContentType, Returns} from "@tsed/schema";
import {Controller} from "@tsed/di";
@Controller("/calendars")
export class CalendarCtrl {
@ContentType(".html") // => 'text/html'
@ContentType("html") // => 'text/html'
@ContentType("json") // => 'application/json'
@ContentType("application/json") // => 'application/json'
@ContentType("png")
getContent(@BodyParams("name") name: string): any {
return "something";
}
@Returns(200, String).ContentType(".html") // => 'text/html'
@Returns(200, String).ContentType("html") // => 'text/html'
@Returns(200, Object).ContentType("json") // => 'application/json'
@Returns(200, Object).ContentType("application/json") // => 'application/json'
@Returns(200, String).ContentType("png")
getContent2(@BodyParams("name") name: string): any {
return "something";
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Header
You can set the response header with the Header decorator:
import {BodyParams} from "@tsed/platform-params";
import {Header, Returns} from "@tsed/schema";
import {Controller} from "@tsed/di";
@Controller("/calendars")
export class CalendarCtrl {
@Header({
"Content-Type": "text/plain",
"Content-Length": 123,
ETag: {
value: "12345",
description: "header description"
}
})
create(@BodyParams("name") name: string): string {
return `Text plain ${name}`;
}
@Returns().Headers({
"Content-Type": "text/plain",
"Content-Length": 123,
ETag: {
value: "12345",
description: "header description"
}
})
create2(@BodyParams("name") name: string): string {
return `Text plain ${name}`;
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# Redirect
Redirects to the URL derived from the specified path, with specified status, a positive integer that corresponds to an HTTP status code . If not specified, status defaults to “302 “Found”.
@Controller("/")
class MyCtrl {
@Redirect("/foo/bar")
@Redirect(301, "http://example.com")
myMethod() {}
}
2
3
4
5
6
Redirects can be a fully-qualified URL for redirecting to a different site:
@Controller("/")
class MyCtrl {
@Redirect("http://google.com")
myMethod() {}
}
2
3
4
5
Redirects can be relative to the root of the host name. For example, if the application is on http://example.com/admin/post/new, the following would redirect to the URL http://example.com/admin:
@Controller("/")
class MyCtrl {
@Redirect("/admin")
myMethod() {}
}
2
3
4
5
Redirects can be relative to the current URL. For example, from http://example.com/blog/admin/ (notice the trailing slash), the following would redirect to the URL http://example.com/blog/admin/post/new.
@Controller("/")
class MyCtrl {
@Redirect("post/new")
myMethod() {}
}
2
3
4
5
Redirecting to post/new from http://example.com/blog/admin (no trailing slash), will redirect to http://example.com/blog/post/new.
If you found the above behavior confusing, think of path segments as directories (with trailing slashes) and files, it will start to make sense.
Path-relative redirects are also possible. If you were on http://example.com/admin/post/new, the following would redirect to http//example.com/admin/post:
@Controller("/")
class MyCtrl {
@Redirect("..")
myMethod() {}
}
2
3
4
5
A back redirection redirects the request back to the referer, defaulting to / when the referer is missing.
class MyCtrl {
@Redirect("back")
myMethod() {}
}
2
3
4
Finally, it also possible to perform redirection programmatically:
import {Controller, Get, ctx} from "@tsed/common";
@Controller("/")
class MyCtrl {
@Get("/")
myMethod(@Context() ctx: Context) {
return ctx.response.redirect("/path/to");
}
}
2
3
4
5
6
7
8
9
# Generics
One of the new usage allowed by the Returns is the support of the Generics from TypeScript.
This feature is basically there to meet the need to generate correct Swagger documentation when using generic templates.
For example, you want to return a generic Document
payload which contains a data (Product) and links to allow a commuter to discover your endpoints linked to this data.
With Returns you can document correctly your endpoint to reflect the correct model:
# Throw exceptions
You can use @tsed/exceptions or similar module to throw an http exception. All exception will be intercepted by the Global error handler and are sent to the client.
Here is an example:
import {PathParams} from "@tsed/platform-params";
import {Get} from "@tsed/schema";
import {Controller} from "@tsed/di";
import {BadRequest} from "@tsed/exceptions";
@Controller("/calendars")
export class CalendarCtrl {
@Get("/:id")
get(@PathParams("id") id: number): any {
if (isNaN(+id)) {
throw new BadRequest("Not a number");
}
return {id};
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
TIP
This example will produce a response with status code 400 and "Not a number" message. GlobalErrorHandlerMiddleware will catch and format the error before sending it to the client.
TIP
See our guide on HttpExceptions to throw customer HttpExceptions
# Inject Request and Response
You can use a decorator to inject the Request in order to retrieve information from the request that you cannot get through decorators. In the same way you can inject the Response instance in order to modify some of its information.
This is not recommended, however, because your will potentially be specific to the platform you are using (Express.js, Koa.js, etc ...)
You can with the Req and Request decorators retrieve the originals request and response as follows:
import {Req, Res} from "@tsed/common";
import {Get} from "@tsed/schema";
import {Controller} from "@tsed/di";
@Controller("/calendars")
export class CalendarCtrl {
@Get("/:id")
get(@Req() request: any, @Res() response: any): void {
console.log(request); // Express.Request or Koa.Request
console.log(response); // Express.Response or Koa.Response
response.status(200).send({id: request.params.id, name: "test"});
}
}
2
3
4
5
6
7
8
9
10
11
12
13
It's also possible to inject the high level PlatformRequest and PlatformResponse:
import {PlatformRequest, PlatformResponse, Req, Res} from "@tsed/common";
import {Get} from "@tsed/schema";
import {Controller} from "@tsed/di";
@Controller("/calendars")
export class CalendarCtrl {
@Get("/:id")
get(@Req() request: PlatformRequest, @Res() response: PlatformResponse): void {
console.log(request); // PlatformRequest
console.log(response); // PlatformResponse
response.status(200).body({id: request.params.id, name: "test"});
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
Finally, it is also possible to retrieve the request and response in Node.js version:
import {Req, Res} from "@tsed/common";
import {Get} from "@tsed/schema";
import {Controller} from "@tsed/di";
import {IncomingMessage, ServerResponse} from "http";
@Controller("/calendars")
export class CalendarCtrl {
@Get("/:id")
get(@Req() request: IncomingMessage, @Res() response: ServerResponse): void {
console.log(request); // IncomingMessage
console.log(response); // ServerResponse
}
}
2
3
4
5
6
7
8
9
10
11
12
13
# Inject next
Use Next decorator isn't recommended because Ts.ED use Promise/Observable to return a response, but something it's required to get next function to chain middlewares.
import {Next, Req, Res} from "@tsed/common";
import {Get} from "@tsed/schema";
import {Controller} from "@tsed/di";
import * as Express from "express";
import {promisify} from "util";
@Controller("/calendars")
export class CalendarCtrl {
@Get("/:id")
async get(@Req() request: Express.Request, @Res() response: Express.Response, @Next() next: Express.NextFunction) {
setTimeout(() => {
myExpressMiddleware(request, response, next);
});
// But it's also possible to do this
await promisify(myExpressMiddleware)(request, response);
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Inject router
Each controller has a PlatformRouter which wrap the original router from [Express.Router](http://expressjs.com/en/guide/routing.html or KoaRouter. You can inject PlatformRouter in your controller to add anything related to the current Router controller.
import {PlatformRouter} from "@tsed/common";
import {Controller} from "@tsed/di";
@Controller("/calendars")
export class CalendarCtrl {
constructor(router: PlatformRouter) {
router.get("/", this.myMethod);
// GET raw router (Express.Router or Koa.Router)
console.log(router.callback());
console.log(router.raw);
console.log(router.getRouter());
}
myMethod(req: any, res: any, next: any) {}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
WARNING
All of these routes added by this way won't be discovered by Ts.ED to produce Swagger documentation.
# Templating
A template engine like EJS (opens new window) or Handlebars (opens new window) can be used to change the response returned by your endpoint. Like Express.js, you need to configure the templating engine so that you can use it later with the View decorator.
Here is an example of a controller which uses the View decorator:
import {View} from "@tsed/platform-views";
import {Get} from "@tsed/schema";
import {Controller} from "@tsed/di";
@Controller("/events")
export class EventsCtrl {
@Get("/:id")
@View("event.ejs")
public get(): any {
return {startDate: new Date(), name: "MyEvent"};
}
}
2
3
4
5
6
7
8
9
10
11
12
And its view:
<h1><%- name %></h1>
<div>Start: <%- startDate %></div>
2
TIP
To configure a template engine with Ts.ED, see our guide to install the engine rendering with Ts.ED.
# Middlewares
The middleware is a function which is called before the route handler. Middleware functions have access to the request and response objects, and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.
TIP
For more details about Middleware declaration see the Middlewares section.
The following decorators lets you add custom middleware on a method or on controller:
# Example
import {Use, UseAfter, UseBefore} from "@tsed/platform-middlewares";
import {PathParams} from "@tsed/platform-params";
import {Get} from "@tsed/schema";
import {Controller} from "@tsed/di";
import {CustomBeforeMdlw, CustomMiddleware} from "../middlewares/middlewares";
@Controller("/calendars")
@UseBefore(CustomBeforeMdlw)
export class CalendarCtrl {
@Get("/:id")
@Use(CustomMiddleware)
get1(@PathParams("id") id: number): any {
return {id};
}
@Get("/:id")
@UseBefore(CustomMiddleware)
get2(@PathParams("id") id: number): any {
return {id};
}
@Get("/:id")
@UseAfter(CustomMiddleware)
get3(@PathParams("id") id: number): any {
return {id};
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# Middleware call sequence
When a request is sent to the server all middlewares added on the Server, Controller or Endpoint will be called while a response isn't sent by one of the middleware in the lifecycle.
TIP
See middlewares section for more information.
# Nested controllers
A controller can have one or more nested controllers. This feature allows you to combine your controllers with each other to define your routes. One controller can be added to multiple controllers, so you can easily reuse the same controller.
This example will produce these following routes:
Verb | Route | Method |
---|---|---|
GET | /rest | RestCtrl.get() |
GET | /rest/calendars | CalendarCtrl.get() |
GET | /rest/calendars/events | EventCtrl.get() |
GET | /rest/events | EventCtrl.get() |
# Inheritance
Ts.ED supports the ES6 inheritance class. So you can declare a controller that implement some generic method and use it on a children class.
To do that just declare a parent controller without the Controller decorator.
import {Get} from "@tsed/schema";
import {QueryParams} from "@tsed/platform-params";
import {SomeService} from "./SomeService";
export abstract class BaseCtrl {
constructor(private someService: SomeService) {}
@Get("/list")
async list(@QueryParams("search") search: any) {
return this.someService.list(search);
}
}
2
3
4
5
6
7
8
9
10
11
12
Then, on your child controller:
import {PathParams} from "@tsed/platform-params";
import {Get} from "@tsed/schema";
import {Controller} from "@tsed/di";
import {BaseCtrl} from "./BaseCtrl";
@Controller("/child")
export abstract class ChildCtrl extends BaseCtrl {
@Get("/:id")
get(@PathParams("id") id: string): any {
return {id: id};
}
}
2
3
4
5
6
7
8
9
10
11
12
# Decorators
Last Updated: 7/3/2022, 7:17:55 PM
Other topics
- Session & cookies
- Passport.js
- Keycloak
- Prisma
- TypeORM
- MikroORM
- Mongoose
- GraphQL
- Socket.io
- Swagger
- AJV
- Multer
- Serve static files
- Templating
- Serverless HTTP
- Seq
- OIDC
- Stripe
- Agenda
- Terminus
- Serverless
- IORedis
- Controllers
- Providers
- Model
- JsonMapper
- Middlewares
- Pipes
- Interceptors
- Authentication
- Hooks
- Exceptions
- Throw HTTP Exceptions
- Cache
- Command
- Response Filter
- Injection scopes
- Custom providers
- Lazy-loading provider
- Custom endpoint decorator
- Testing
- Customize 404