'use strict' ; import Config from '../config' ; import { Request , Response } from 'express' ; import { Monitoring } from '@Monitoring/Monitoring' ; import { IsNotNullOrEmpty } from '@Tools/Misc' ; import { Logger } from '@Tools/Logging' ; export enum HTTPStatusCode { OK = 200 , Found = 302 , BadRequest = 400 , Unauthorized = 401 , Forbidden = 403 , NotFound = 404 } ; export class RESTResponse { IsFailure : boolean ; Status : string ; HTTPStatus : number ; Data : any ; private _request : Request ; private _response : Response ; private _additionalFields : Map < string , any > = new Map < string , any > ( ) ; constructor ( pReq , pResp ) { this . _request = pReq ; this . _response = pResp ; this . IsFailure = false ; this . Status = 'success' ; this . HTTPStatus = HTTPStatusCode . OK ; } ; getRequest ( ) { return this . _request ; } ; getResponse ( ) { return this . _response ; } ; private _authToken : string = null ; getAuthToken ( ) { if ( this . _authToken === null ) { const auth = this . _request . headers . authorization ; if ( auth ) { if ( auth . toLowerCase ( ) . startsWith ( 'bearer ' ) ) { this . _authToken = auth . substr ( 7 ) ; } else { this . _authToken = auth ; } } } return this . _authToken ; } respondSuccess ( ) { this . Status = 'success' ; return this ; } ; respondFailure ( msg1 , msg2 ? ) { this . Status = 'failure' ; this . IsFailure = true ; this . _additionalFields . set ( 'error' , msg1 ) ; if ( msg2 ) { this . _additionalFields . set ( 'errorInfo' , msg2 ) ; } return this ; } ; addAdditionalField ( pFieldName , pFieldValue ) { this . _additionalFields . set ( pFieldName , pFieldValue ) ; } ; buildRESTResponse ( ) { let responseData ; if ( this . IsFailure ) { if ( Config [ "metaverse-server" ] [ "http-error-on-failure" ] ) { const errorHeader = Config [ "metaverse-server" ] [ "error-header" ] ; const errorAction = this . _request . get ( errorHeader ) ; if ( errorAction && errorAction . toLowerCase ( ) === "badrequest" ) { this . _response . statusCode = HTTPStatusCode . BadRequest ; } ; } ; responseData = { 'status' : 'failure' } ; Monitoring . event ( 'apiErrors' , 1 ) ; } else { responseData = { 'status' : this . Status , } ; } ; if ( IsNotNullOrEmpty ( this . Data ) ) { responseData . data = this . Data ; } ; if ( this . _additionalFields . size > 0 ) { this . _additionalFields . forEach ( ( val , key ) => { responseData [ key ] = val ; } ) ; } ; return responseData ; } ; } ;