# 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 {Controller, Get} from "@tsed/common";

@Controller("/calendars")
export class CalendarCtrl {
  @Get()
  findAll(): string {
    return "This action returns all calendars";
  }
}
1
2
3
4
5
6
7
8
9

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 {
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 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/common";

@Configuration({
  mount: {
    "/rest/v0": "./controllers/v0/**/*.ts",
    "/rest/v1": "./controllers/v1/**/*.ts"
  }
})
export class Server {
}
1
2
3
4
5
6
7
8
9
10

# 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 {Controller, Get, PathParams} from "@tsed/common";

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"
    };
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# Observable/Stream/Buffer

Also, Ts.ED support function that return Observable, Stream or Buffer.

import {Controller, Get, PlatformResponse, Res} from "@tsed/common";
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");
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# 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 {Controller, Get, QueryParams, Res} from "@tsed/common";
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;
  }
}
1
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

# 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 {Controller, Get, Post} from "@tsed/common";

@Controller("/calendars")
export class CalendarCtrl {
  @Get("/:id")
  @Get("/alias/:id")
  @Post("/:id/complexAlias")
  async get(): Promise<any> {
    return "Return something";
  }
}
1
2
3
4
5
6
7
8
9
10
11

# 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 {Controller, Get, PathParams} from "@tsed/common";

@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
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

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:

    Finally, BodyParams accepts to give a IParamOptions object as parameter to change the decorator behavior:

    import {BodyParams, Post} from "@tsed/common";
    
    class MyController {
      @Post()
      async create(@BodyParams({expression: "user", useConverter: false}) body: T): Promise<T> {
        console.log("payload", body);
    
        return body;
      }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10

    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) {}
    }
    
    1
    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, Controller, Post} from "@tsed/common";
    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;
      }
    }
    
    1
    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

    Add Any decorator to fix the issue.

    # Raw Body v6.20.0+

    RawBodyParams decorator provides you quick access to the request.rawBody:

    import {Controller, Post, RawBodyParams} from "@tsed/common";
    
    @Controller("/calendars")
    export class CalendarCtrl {
      @Post()
      post(@RawBodyParams() payload: Buffer): string {
        return payload.toString("utf8");
      }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9

    WARNING

    There is no performed input validation and deserialization when using the RawBodyParams !

    # Headers

    HeaderParams decorator provides you quick access to the request.get():

    import {Controller, Get, HeaderParams} from "@tsed/common";
    
    @Controller("/calendars")
    export class CalendarCtrl {
    
      @Get()
      get(@HeaderParams("x-token") token: string): string {
        console.log("token", token);
    
        return token;
      }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12

    # 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 {Controller, Get, Locals, Middleware, UseBefore, View} from "@tsed/common";
    
    @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"
        };
      }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23

    # 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 {Controller, Get, PathParams} from "@tsed/common";
    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`;
      }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10

    WARNING

    Validation require the @tsed/ajv plugins to work.

    npm install --save @tsed/ajv
    
    1

    Supported decorators:

    # Response

    # Decorators

    # Status

    You can change the default response status with the Status decorator:

    import {BodyParams, Controller, Put} from "@tsed/common";
    import {Status} from "@tsed/schema";
    
    interface Calendar {
      id: string;
      name: string;
    }
    
    @Controller("/calendars")
    export class CalendarCtrl {
      @Put("/")
      @Status(201)
      create(@BodyParams("name") id: string): Calendar {
        return {id: "2", name: "test"};
      }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16

    # Content Type

    You can set the response content type with the ContentType decorator:

    import {BodyParams, Controller} from "@tsed/common";
    import {ContentType, Returns} from "@tsed/schema";
    
    @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";
      }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23

    You can set the response header with the Header decorator:

    import {BodyParams, Controller} from "@tsed/common";
    import {Header, Returns} from "@tsed/schema";
    
    @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}`;
      }
    }
    
    1
    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

    # 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() {}
    }
    
    1
    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() {}
    }
    
    1
    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() {}
    }
    
    1
    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() {}
    }
    
    1
    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() {}
    }
    
    1
    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() {}
    }
    
    
    1
    2
    3
    4
    5

    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")
      }
    }
    
    1
    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 {Controller, Get, PathParams} from "@tsed/common";
      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};
        }
      }
      
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14

      TIP

      This example will produce a response with status code 400 and "Not a number" message. Unable to find something: symbolName === "GlobalErrorHandlerMiddleware" will catch and format the error before sending it to the client.

      # 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 {Controller, Get, Req, Res} from "@tsed/common";
      
      @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"});
        }
      }
      
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16

      It's also possible to inject the high level PlatformRequest and PlatformResponse:

      import {Controller, Get, Req, Res, PlatformRequest, PlatformResponse} from "@tsed/common";
      
      @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"});
        }
      }
      
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17

      Finally, it is also possible to retrieve the request and response in Node.js version:

      import {Controller, Get, Req, Res} from "@tsed/common";
      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
        }
      }
      
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14

      # 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 {Controller, Get, Next, Req, Res} from "@tsed/common";
      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)
        }
      }
      
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20

      # 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 {Controller, PlatformRouter} from "@tsed/common";
      
      @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) {
        }
      }
      
      1
      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 {Controller, Get, View} from "@tsed/common";
      
      @Controller("/events")
      export class EventsCtrl {
        @Get("/:id")
        @View("event.ejs")
        public get(): any {
          return {startDate: new Date(), name: "MyEvent"};
        }
      }
      
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10

      And its view:

      <h1><%- name %></h1>
      <div>
          Start: <%- startDate %>
      </div>
      
      1
      2
      3
      4

      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 {Controller, Get, PathParams, Use, UseAfter, UseBefore} from "@tsed/common";
      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};
        }
      }
      
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24

      # 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, QueryParams} from "@tsed/common";
        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);
          }
        }
        
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12

        Then, on your child controller:

        import {Controller, Get, PathParams} from "@tsed/common";
        import {BaseCtrl} from "./BaseCtrl";
        
        @Controller("/child")
        export abstract class ChildCtrl extends BaseCtrl {
          @Get("/:id")
          get(@PathParams("id") id: string): any {
            return {id: id};
          }
        }
        
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10

        # Decorators

        Last Updated: 8/3/2021, 3:39:18 PM

        Other topics