diff --git a/src/api/integrations/event/webhook/webhook.controller.ts b/src/api/integrations/event/webhook/webhook.controller.ts index 269a47c0..ce709c3d 100644 --- a/src/api/integrations/event/webhook/webhook.controller.ts +++ b/src/api/integrations/event/webhook/webhook.controller.ts @@ -5,7 +5,7 @@ import { wa } from '@api/types/wa.types'; import { configService, Log, Webhook } from '@config/env.config'; import { Logger } from '@config/logger.config'; import { BadRequestException } from '@exceptions'; -import axios from 'axios'; +import axios, { AxiosInstance } from 'axios'; import { isURL } from 'class-validator'; import { EmitData, EventController, EventControllerInterface } from '../event.controller'; @@ -117,12 +117,12 @@ export class WebhookController extends EventController implements EventControlle headers: webhookHeaders as Record | undefined, }); - await httpService.post('', webhookData); + await this.retryWebhookRequest(httpService, webhookData, `${origin}.sendData-Webhook`, baseURL, serverUrl); } } catch (error) { this.logger.error({ local: `${origin}.sendData-Webhook`, - message: error?.message, + message: `Todas as tentativas falharam: ${error?.message}`, hostName: error?.hostname, syscall: error?.syscall, code: error?.code, @@ -158,12 +158,18 @@ export class WebhookController extends EventController implements EventControlle if (isURL(globalURL)) { const httpService = axios.create({ baseURL: globalURL }); - await httpService.post('', webhookData); + await this.retryWebhookRequest( + httpService, + webhookData, + `${origin}.sendData-Webhook-Global`, + globalURL, + serverUrl, + ); } } catch (error) { this.logger.error({ local: `${origin}.sendData-Webhook-Global`, - message: error?.message, + message: `Todas as tentativas falharam: ${error?.message}`, hostName: error?.hostname, syscall: error?.syscall, code: error?.code, @@ -177,4 +183,51 @@ export class WebhookController extends EventController implements EventControlle } } } + + private async retryWebhookRequest( + httpService: AxiosInstance, + webhookData: any, + origin: string, + baseURL: string, + serverUrl: string, + maxRetries = 10, + delaySeconds = 30, + ): Promise { + let attempts = 0; + + while (attempts < maxRetries) { + try { + await httpService.post('', webhookData); + if (attempts > 0) { + this.logger.log({ + local: `${origin}`, + message: `Sucesso no envio após ${attempts + 1} tentativas`, + url: baseURL, + }); + } + return; + } catch (error) { + attempts++; + + this.logger.error({ + local: `${origin}`, + message: `Tentativa ${attempts}/${maxRetries} falhou: ${error?.message}`, + hostName: error?.hostname, + syscall: error?.syscall, + code: error?.code, + error: error?.errno, + stack: error?.stack, + name: error?.name, + url: baseURL, + server_url: serverUrl, + }); + + if (attempts === maxRetries) { + throw error; + } + + await new Promise((resolve) => setTimeout(resolve, delaySeconds * 1000)); + } + } + } }