import { Injectable, Inject, HttpException } from '@nestjs/common'; import { SignatureV4 } from '@aws-sdk/signature-v4'; import { Sha256 } from '@aws-crypto/sha256-js'; import { defaultProvider } from '@aws-sdk/credential-provider-node'; import axios, { AxiosResponse, Method } from 'axios'; import { DadosferaLogger } from '@dadosfera/dadosfera-logs'; import { RequestUser } from '../../decorators/user.decorator'; import { CONNECTIONS_API_CONFIG } from './connections-api.config'; @Injectable() export class ConnectionsApiService { private signer: SignatureV4; private logger: any; constructor(@Inject(DadosferaLogger) dadosferaLogger: DadosferaLogger) { this.logger = dadosferaLogger.logger; this.signer = new SignatureV4({ service: 'execute-api', region: CONNECTIONS_API_CONFIG.region, credentials: defaultProvider(), sha256: Sha256, }); } async proxy( method: string, path: string, user: RequestUser, body?: any, query?: Record, ): Promise { const baseUrl = CONNECTIONS_API_CONFIG.getUrl(); const url = new URL(`${baseUrl}${path}`); if (query) { Object.entries(query).forEach(([key, value]) => { if (value !== undefined && value !== null) { url.searchParams.set(key, String(value)); } }); } const headers: Record = { host: url.hostname, 'content-type': 'application/json', customer_name: user.customer_name || '', customer_id: user.customer_id || '', 'x-user-id': user.user_id || '', 'x-username': user.username || '', 'x-customer-tier': user.customer_tier || '', 'x-customer-id': user.customer_id || '', }; const requestToSign = { method: method.toUpperCase(), protocol: url.protocol, hostname: url.hostname, port: url.port ? parseInt(url.port, 10) : undefined, path: url.pathname + url.search, headers, body: body ? JSON.stringify(body) : undefined, }; try { const signedRequest = await this.signer.sign(requestToSign); const response: AxiosResponse = await axios({ method: method as Method, url: url.href, headers: signedRequest.headers as Record, data: body, timeout: CONNECTIONS_API_CONFIG.timeout, validateStatus: () => true, }); if (response.status >= 400) { throw new HttpException(response.data, response.status); } return response.data; } catch (error) { this.logger.error('Connections API proxy error', { error: error.message, path, method: method.toUpperCase(), }); if (error instanceof HttpException) { throw error; } if (error.response) { throw new HttpException(error.response.data, error.response.status); } if (error.code === 'ECONNREFUSED') { throw new HttpException('Connections API service unavailable', 503); } if (error.code === 'ETIMEDOUT' || error.code === 'ECONNABORTED') { throw new HttpException('Connections API request timeout', 504); } throw new HttpException('Internal server error', 500); } } }