import { HttpException , HttpStatus } from '@nestjs/common' ; import * as cls from 'cls-hooked' ; import uuid from 'uuid' ; import { User } from '@ngx-starter-kit/models' ; export class RequestContext { readonly id : number ; request : Request ; response : Response ; constructor ( request , response ) { this . id = Math . random ( ) ; this . request = request ; this . response = response ; } static currentRequestContext ( ) { const session = cls . getNamespace ( RequestContext . name ) ; if ( session && session . active ) { return session . get ( RequestContext . name ) ; } return null ; } static currentRequest ( ) { const requestContext = RequestContext . currentRequestContext ( ) ; if ( requestContext ) { return requestContext . request ; } return null ; } static currentUser ( throwError ? ) { const requestContext = RequestContext . currentRequestContext ( ) ; if ( requestContext ) { const user = requestContext . request [ 'user' ] ; if ( user ) { return user ; } } if ( throwError ) { throw new HttpException ( 'Unauthorized' , HttpStatus . UNAUTHORIZED ) ; } return null ; } static currentToken ( throwError ? ) { const requestContext = RequestContext . currentRequestContext ( ) ; if ( requestContext ) { return requestContext . request [ 'token' ] ; } if ( throwError ) { throw new HttpException ( 'Unauthorized' , HttpStatus . UNAUTHORIZED ) ; } return null ; } }