import { lastValueFrom , timeout } from 'rxjs' ; import { Inject , Injectable } from '@nestjs/common' ; import { ClientProxy } from '@nestjs/microservices' ; import { validateDto } from '@fc/common' ; import { ConfigService , validationOptions } from '@fc/config' ; import { BridgePayload , BridgeProtocol } from '@fc/hybridge-http-proxy' ; import { LoggerService } from '@fc/logger' ; import { HttpProxyProtocol } from '@fc/microservices' ; import { RabbitmqConfig } from '@fc/rabbitmq' ; import { BridgeHttpProxyProtocolDto } from '../dto' ; import { BridgeHttpProxyMissingVariableException , BridgeHttpProxyRabbitmqException , } from '../exceptions' ; @ Injectable ( ) export class BridgeHttpProxyService { constructor ( private readonly logger , private readonly config , @ Inject ( 'BridgeProxyBroker' ) private readonly broker ) { this . logger . setContext ( this . constructor . name ) ; } param originalUrl param method param headers param body returns async proxyRequest ( originalUrl , method , headers , body ? ) { let idpResponse ; const message = this . createMessage ( originalUrl , method , headers , body ) ; const { requestTimeout } = this . config . get < RabbitmqConfig > ( 'BridgeProxyBroker' ) ; this . logger . debug ( 'BrokerProxyController.proxyRequest()' ) ; const order = this . broker . send ( HttpProxyProtocol . Commands . HTTP_PROXY , message ) . pipe ( timeout ( requestTimeout ) ) ; try { idpResponse = await lastValueFrom ( order ) ; } catch ( error ) { this . logger . trace ( { error } ) ; throw new BridgeHttpProxyRabbitmqException ( ) ; } const dtoProtocolErrors = await validateDto ( idpResponse , BridgeHttpProxyProtocolDto , validationOptions ) ; if ( dtoProtocolErrors . length ) { this . logger . trace ( { dtoProtocolErrors } ) ; throw new BridgeHttpProxyMissingVariableException ( ) ; } return idpResponse ; } param originalUrl param method param headers param body returns private createMessage ( originalUrl , method , headers , data ? ) { const { host , 'x-forwarded-proto' : xForwardedProto } = headers ; const url = `${ xForwardedProto }://${ host }${ originalUrl }` ; return { headers , method , data , url , } ; } param res param headers setHeaders ( res , headers ) { Object . entries ( headers ) . forEach ( ( [ key , value ] ) => { res . set ( key , value ) ; } ) ; } }