import { Body , Controller , Get , Headers , Post , Req , Res } from '@nestjs/common' ; import { validateDto } from '@fc/common' ; import { validationOptions } from '@fc/config' ; import { BridgeError , BridgeProtocol , BridgeResponse , MessageType , } from '@fc/hybridge-http-proxy' ; import { LoggerService } from '@fc/logger' ; import { BridgeHttpProxyErrorDto , BridgeHttpProxyResponseDto } from '../dto' ; import { BridgeHttpProxyRoutes } from '../enums' ; import { BridgeHttpProxyCsmrException , BridgeHttpProxyMissingVariableException , } from '../exceptions' ; import { BridgeHttpProxyService } from '../services' ; @ Controller ( ) export class BridgeHttpProxyController { constructor ( private readonly logger , private readonly broker ) { this . logger . setContext ( this . constructor . name ) ; } param { originalUrl param headers param res @ Get ( BridgeHttpProxyRoutes . WILDCARD ) async get ( @ Req ( ) req , @ Headers ( ) headers , @ Res ( ) res ) { const { originalUrl } = req ; const { host , 'x-forwarded-proto' : xForwardedProto } = headers ; this . logger . debug ( `GET ${ xForwardedProto }://${ host }${ originalUrl }` ) ; await this . allRequest ( req , headers , res ) ; } param { originalUrl param headers param body param res @ Post ( BridgeHttpProxyRoutes . WILDCARD ) async post ( @ Req ( ) req , @ Headers ( ) headers , @ Res ( ) res , @ Body ( ) body ) { const { originalUrl } = req ; const { host , 'x-forwarded-proto' : xForwardedProto } = headers ; this . logger . debug ( `POST ${ xForwardedProto }://${ host }${ originalUrl }` ) ; await this . allRequest ( req , headers , res , body ) ; } private async allRequest ( req , headers , res , body ? ) { const { originalUrl , method } = req ; const response = await this . broker . proxyRequest ( originalUrl , method , headers , body ) ; const { type , data } = response ; if ( type === MessageType . DATA ) { await this . handleMessage ( res , data ) ; } else { await this . handleError ( data ) ; } } async handleMessage ( res , message ) { const dtoProtocolErrors = await validateDto ( message , BridgeHttpProxyResponseDto , validationOptions ) ; if ( dtoProtocolErrors . length ) { throw new BridgeHttpProxyMissingVariableException ( ) ; } const { headers , data , status } = message as BridgeResponse ; this . broker . setHeaders ( res , headers ) ; res . status ( status ) . send ( data ) ; } async handleError ( error ) { const dtoProtocolErrors = await validateDto ( error , BridgeHttpProxyErrorDto , validationOptions ) ; if ( dtoProtocolErrors . length ) { throw new BridgeHttpProxyMissingVariableException ( ) ; } throw new BridgeHttpProxyCsmrException ( error as BridgeError ) ; } }