# Context

Ts.ED provides an util to get request, response, to store and share data along all middlewares/endpoints during a request with PlatformContext . This context is created by Ts.ED when the request is handled by the server.

It contains some information as following:

  • The request and response abstraction layer with PlatformRequest and PlatformResponse (since v5.64.0+),
  • The request id,
  • The request container used by the Ts.ED DI. It contains all services annotated with @Scope(ProviderScope.REQUEST),
  • The current EndpointMetadata context resolved by Ts.ED during the request,
  • The data returned by the previous endpoint if you use multiple handlers on the same route. By default data is empty.
  • The ContextLogger to log some information related to the request and his id.

Here is an example:

import {Context} from "@tsed/platform-params";
import {Middleware, UseBefore} from "@tsed/platform-middlewares";
import {Get} from "@tsed/schema";
import {Controller} from "@tsed/di";
import {Forbidden} from "@tsed/exceptions";
import {AuthToken} from "../domain/auth/AuthToken";

@Middleware()
class AuthTokenMiddleware {
  use(@Context() ctx: Context) {
    if (!ctx.has("auth")) {
      ctx.set("auth", new AuthToken(ctx.request));
    }

    try {
      ctx.get("auth").claims(); // check token
    } catch (er) {
      throw new Forbidden("Access forbidden - Bad token");
    }
  }
}

@Controller("/")
@UseBefore(AuthTokenMiddleware) // protect all routes for this controller
class MyCtrl {
  @Get("/")
  get(@Context() context: Context, @Context("auth") auth: AuthToken) {
    context.logger.info({event: "auth", auth}); // Attach log to the request
  }
}
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
30

TIP

ContextLogger is attached to the context ctx.logger. The ContextLogger stores all logs and Ts.ED prints ( flushes) all logs after the response is sent by the server. The approach optimizes performance by first sending in the response and then printing all logs.

# Endpoint metadata

EndpointMetadata is the current controller method executed by the request. Middleware can access to this endpoint metadata when you use the middleware over a controller method. By accessing to the EndpointMetadata you are able to:

import {StoreSet} from "@tsed/core";
import {Get, Controller, Middleware, Context, EndpointInfo, Use, Returns} from "@tsed/common";
import {Resource} from "./Resource";

@Middleware()
export class MyMiddleware {
  use(@Context() ctx: Context) {
    console.log(ctx.endpoint); // Endpoint Metadata
    console.log(ctx.endpoint.targetName); // MyCtrl
    console.log(ctx.endpoint.propertyKey); // getMethod
    console.log(ctx.endpoint.type); // Resource
    console.log(ctx.endpoint.store.get("options")); // options
  }
}

@Controller("/resources")
class MyCtrl {
  @Get("/:id")
  @Use(MyMiddleware)
  @Returns(200, Resource)
  @StoreSet("options", "options")
  getMethod(): Resource {
    return new Resource();
  }
}
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

# Request and Response abstraction

PlatformContext provide a PlatformRequest and PlatformResponse classes which are an abstraction layer of the targeted platform (Express.js, Koa.js, etc...).

By using the PlatformContext interface, your code will be compatible with any platform. But, the abstraction doesn't or cannot provide all necessaries properties or methods. It's also possible to get the original request or response by different ways.

import {Middleware, Context, Req, Res} from "@tsed/common";

@Middleware()
export class MyMiddleware {
  use(@Req() req: Req, @Res() res: Res, @Context() ctx: Context) {
    // abstraction
    console.log(ctx.request); // PlatformRequest
    console.log(ctx.response); // PlatformResponse

    // by decorator
    console.log(req); // Express.Request
    console.log(res); // Express.Response

    // by
    console.log(ctx.request.raw); // Express.Request
    console.log(ctx.response.raw); // Express.Request

    // by method
    console.log(ctx.getRequest<Express.Request>()); // Express.Request
    console.log(ctx.getResponse<Express.Response>()); // Express.Response
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# PlatformRequest

PlatformRequest provide high level methods and properties to get request information. His interface is the following:

class PlatformRequest<T = Req> {
  raw: T;

  get secure(): boolean;

  get url(): string;

  get route(): string;

  get headers(): IncomingHttpHeaders;

  get method(): string;

  get body(): {[key: string]: any};

  get rawBody(): {[key: string]: any};

  get cookies(): {[key: string]: any};

  get params(): {[key: string]: any};

  get query(): {[key: string]: any};

  get session(): {[key: string]: any} | undefined;

  get(name: string): string | undefined; // get header
  getHeader(name: string): string | undefined; // get header
  accepts(mime?: string | string[]): string | string[] | false;
  isAborted(): boolean;
}
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
30

# Get request headers

import {Controller, Context} from "@tsed/common";

@Controller("/")
export class MyController {
  @Get("/")
  get(@Context() ctx: Context) {
    ctx.request.headers; // return all headers
    ctx.get("host"); // return host header
    ctx.getHeader("host"); // return host header
  }
}
1
2
3
4
5
6
7
8
9
10
11

# Get request params/body/query/cookies/session

import {Controller, Context} from "@tsed/common";

@Controller("/")
export class MyController {
  @Get("/")
  get(@Context() ctx: Context) {
    ctx.request.body; // return body payload
    ctx.request.params; // return path params
    ctx.request.query; // return query params
    ctx.request.cookies; // return cookies
    ctx.request.session; // return session
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# PlatformResponse

PlatformResponse provide high level methods like .body() to send any data to your consumer. This method can get Boolean, Number, String, Date, Object, Array or Stream as input type and determine the correct way to send the response to your consumer.

His interface is the following:

class PlatformResponse {
  raw: Res;

  get statusCode(): number;

  get locals(): Record<string, any>;

  status(status: number): this;

  setHeaders(headers: {[key: string]: any}): this;

  contentType(contentType: string): this;

  redirect(status: number, url: string): this;

  location(location: string): this;

  stream(data: ReadableStream | any): this;

  render(path: string, options?: any): Promise<string>;

  body(data: any): this;

  onEnd(cb: Function): void;

  destroy(): void;

  cookie(name: string, value: string | null, opts?: TsED.SetCookieOpts): this;
}
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

# Set response headers

import {Controller, Context} from "@tsed/common";

@Controller("/")
export class MyController {
  @Get("/")
  get(@Context() ctx: Context) {
    // set headers, content-type and status
    ctx.response.setHeaders({"x-header": "header"});
    ctx.response.contentType("application/json");
    ctx.response.status(201);
  }
}
1
2
3
4
5
6
7
8
9
10
11
12

Can be also done by returning a response like object:

import {Controller, Context} from "@tsed/common";

@Controller("/")
export class MyController {
  @Get("/")
  get(@Context() ctx: Context) {
    return {
      statusText: "OK",
      status: 200,
      headers: {},
      data: {}
    };
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import {Controller, Context} from "@tsed/common";

@Controller("/")
export class MyController {
  @Get("/")
  get(@Context() ctx: Context) {
    // set
    ctx.response.cookie("locale", "fr-FR");

    // clear
    ctx.response.cookie("locale", null);
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# Set response body

import {Controller, Context} from "@tsed/common";

@Controller("/")
export class MyController {
  @Get("/")
  get(@Context() ctx: Context) {
    // equivalent to ctx.getResponse().send()
    ctx.response.body(null);
    ctx.response.body(undefined);
    ctx.response.body(true);
    ctx.response.body(false);

    // equivalent to ctx.getResponse().json()
    ctx.response.body({});
    ctx.response.body([]);
    ctx.response.body(new Date());

    // equivalent to readableStream.pipe(ctx.response.raw)
    ctx.response.body(readableStream);
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

But prefer returning payload from your method! Ts.ED will handle all data type (Buffer/Stream/Data/Promise/Observable).

# Manipulate original response

You can retrieve the Express\Koa response by using ctx.getResponse() method:

import {Controller, Context} from "@tsed/common";

@Controller("/")
export class MyController {
  @Get("/")
  get(@Context() ctx: Context) {
    // Express.js
    ctx.getResponse<Express.Response>().status(201).send("Hello");
  }
}
1
2
3
4
5
6
7
8
9
10

# AsyncHook context

Inject PlatformContext from a controller and forward the context to another service could be a pain point. See example:

@Injectable()
export class CustomRepository {
  async findById(id: string, ctx: PlatformContext) {
    ctx.logger.info("Where are in the repository");
    return {
      id,
      headers: this.$ctx?.request.headers
    };
  }
}

@Controller("/async-hooks")
export class AsyncHookCtrl {
  @Inject()
  repository: CustomRepository;

  @Get("/:id")
  async get(@PathParams("id") id: string, @Context() ctx: PlatformContext) {
    return this.repository.findById(id, ctx);
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

Since v6.26.0, Ts.ED provide a way to get the PlatformContext directly from a Service called by a controller, using the AsyncLocalStorage (opens new window) provided by Node.js.

This feature is experimental but in reality, the API is stable and the benefit to use it is here!

If you have a Ts.ED version under v6.113.0, you have to install the @tsed/async-hook-context package if your environment have the required Node.js (v13+) version.

npm install --save @tsed/async-hook-context
1

Since v6.113.0, the AsyncLocalStorage (opens new window) is automatically enabled.

With this feature, you can inject directly the PlatformContext in the service without injecting it in the controller:

import {Injectable, Controller, InjectContext} from "@tsed/di";
import {PlatformContext} from "@tsed/common";

@Injectable()
export class CustomRepository {
  @InjectContext()
  protected $ctx?: PlatformContext;

  async findById(id: string) {
    this.ctx?.logger.info("Where are in the repository");

    return {
      id,
      headers: this.$ctx?.request.headers
    };
  }
}

@Controller("/async-hooks")
export class AsyncHookCtrl {
  @Inject()
  repository: CustomRepository;

  @Get("/:id")
  async get(@PathParams("id") id: string) {
    return this.repository.findById(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
25
26
27
28

To run a method with context in your unit test, you can use the PlatformAsyncHookContext .

import {runInContext} from "@tsed/di";
import {PlatformContext} from "@tsed/common";
import {CustomRepository} from "./CustomRepository";

describe("CustomRepository", () => {
  beforeEach(() => PlatformTest.create());
  afterEach(() => PlatformTest.reset());

  it("should run method with the ctx", async () => {
    const ctx = PlatformTest.createRequestContext();
    const service = PlatformTest.get<CustomRepository>(CustomRepository);

    ctx.request.headers = {
      "x-api": "api"
    };

    const result = await runInContext(ctx, () => service.findById("id"));

    expect(result).toEqual({
      id: "id",
      headers: {
        "x-api": "api"
      }
    });
  });
});
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

Last Updated: 10/24/2024, 6:33:40 AM

Other topics