# Context Decorator

Module
import { Context } from "@tsed/common"
Source/packages/common/src/mvc/decorators/params/context.ts

# Overview

function Context(expression: string): ParameterDecorator;
function Context(): ParameterDecorator;
type Context = RequestContext;
Param Type Description
expression string The path of the property to get.

# Description

Context decorator return the RequestContext created by Ts.ED when request is handled by the server.

It contains some information as following:

  • The request id,
  • The request container used by the Ts.ED DI. It contain all services annotated with @Scope(ProviderScope.REQUEST),
  • The current EndpointMetadata resolved by Ts.ED during the request,
  • The data return by the previous endpoint if you use multiple handler on the same route. By default data is empty.

TIP

The RequestContext inherit from Map class. So you can store any information with.

# Example

@Middleware()
class AuthTokenMiddleware {
  use(@Req() request: Express.Request, @Context() context: RequestContext) {
     if (!context.has('auth')){
       context.set('auth', new AuthToken(request))
     }

     try {
       context.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('auth') auth: AuthToken) {
      console.log('auth', auth);
      console.log('auth.accessToken', auth.accessToken);
      console.log('auth.idToken', auth.idToken);
   }
}
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

:::