# Context Decorator operation input

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

# Overview

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

# Description

Context decorator return the 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 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 inherit from Map class. So you can store any information with.

# Example

@Middleware()
class AuthTokenMiddleware {
  use(@Req() request: Req, @Context() context: PlatformContext) {
     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