mirror of
https://github.com/dadosfera/maestro.git
synced 2026-11-16 17:39:07 +00:00
95 lines
2.6 KiB
TypeScript
95 lines
2.6 KiB
TypeScript
import { Injectable, Inject, HttpException } from '@nestjs/common';
|
|
import axios, { AxiosResponse, Method } from 'axios';
|
|
import { DadosferaLogger } from '@dadosfera/dadosfera-logs';
|
|
|
|
import { RequestUser } from '../../decorators/user.decorator';
|
|
import { AUTODRIVE_ASSISTANT_CONFIG } from './autodrive-assistant.config';
|
|
|
|
@Injectable()
|
|
export class AutodriveAssistantService {
|
|
private logger: any;
|
|
|
|
constructor(
|
|
@Inject(DadosferaLogger) dadosferaLogger: DadosferaLogger,
|
|
) {
|
|
this.logger = dadosferaLogger.logger;
|
|
}
|
|
|
|
async proxy(
|
|
method: string,
|
|
path: string,
|
|
user: RequestUser,
|
|
body?: any,
|
|
query?: Record<string, any>
|
|
): Promise<any> {
|
|
if (!user.customer_id) {
|
|
throw new HttpException('Customer ID is required for autodrive assistant operations', 400);
|
|
}
|
|
|
|
const baseUrl = AUTODRIVE_ASSISTANT_CONFIG.getUrl(user.customer_name);
|
|
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<string, string> = {
|
|
'content-type': 'application/json',
|
|
'Authorization': user.access_token,
|
|
};
|
|
|
|
this.logger.info('Proxying request to autodrive-assistant', {
|
|
method: method.toUpperCase(),
|
|
path,
|
|
customer_id: user.customer_id,
|
|
user_id: user.user_id,
|
|
});
|
|
|
|
try {
|
|
const response: AxiosResponse = await axios({
|
|
method: method as Method,
|
|
url: url.href,
|
|
headers,
|
|
data: body,
|
|
timeout: AUTODRIVE_ASSISTANT_CONFIG.timeout,
|
|
validateStatus: () => true,
|
|
});
|
|
|
|
if (response.status >= 400) {
|
|
throw new HttpException(response.data, response.status);
|
|
}
|
|
|
|
return response.data;
|
|
} catch (error) {
|
|
this.logger.error('Autodrive Assistant API proxy error', {
|
|
error: error.message,
|
|
status: error.response?.status,
|
|
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('Autodrive Assistant API service unavailable', 503);
|
|
}
|
|
|
|
if (error.code === 'ETIMEDOUT' || error.code === 'ECONNABORTED') {
|
|
throw new HttpException('Autodrive Assistant API request timeout', 504);
|
|
}
|
|
|
|
throw new HttpException('Internal server error', 500);
|
|
}
|
|
}
|
|
}
|