diff --git a/backend/src/helpers/Debounce.ts b/backend/src/helpers/Debounce.ts new file mode 100644 index 0000000..80665d9 --- /dev/null +++ b/backend/src/helpers/Debounce.ts @@ -0,0 +1,41 @@ +interface Timeout { + id: number; + timeout: NodeJS.Timeout; +} + +const timeouts: Timeout[] = []; + +const findAndClearTimeout = (ticketId: number) => { + if (timeouts.length > 0) { + const timeoutIndex = timeouts.findIndex(timeout => timeout.id === ticketId); + + if (timeoutIndex !== -1) { + clearTimeout(timeouts[timeoutIndex].timeout); + timeouts.splice(timeoutIndex, 1); + } + } +}; + +const debounce = ( + func: { (): Promise; (...args: never[]): void }, + wait: number, + ticketId: number +) => { + return function executedFunction(...args: never[]): void { + const later = () => { + findAndClearTimeout(ticketId); + func(...args); + }; + + findAndClearTimeout(ticketId); + + const newTimeout = { + id: ticketId, + timeout: setTimeout(later, wait) + }; + + timeouts.push(newTimeout); + }; +}; + +export { debounce }; diff --git a/backend/src/services/WbotServices/wbotMessageListener.ts b/backend/src/services/WbotServices/wbotMessageListener.ts index 649fb8a..5a6a968 100644 --- a/backend/src/services/WbotServices/wbotMessageListener.ts +++ b/backend/src/services/WbotServices/wbotMessageListener.ts @@ -20,6 +20,7 @@ import { logger } from "../../utils/logger"; import CreateOrUpdateContactService from "../ContactServices/CreateOrUpdateContactService"; import FindOrCreateTicketService from "../TicketServices/FindOrCreateTicketService"; import ShowWhatsAppService from "../WhatsappService/ShowWhatsAppService"; +import { debounce } from "../../helpers/Debounce"; interface Session extends Client { id?: number; @@ -165,9 +166,19 @@ const verifyQueue = async ( const body = `\u200e ${greetingMessage}\n${options}`; - const sentMessage = await wbot.sendMessage(`${contact.number}@c.us`, body); + const debouncedSentMessage = debounce( + async () => { + const sentMessage = await wbot.sendMessage( + `${contact.number}@c.us`, + body + ); + verifyMessage(sentMessage, ticket, contact); + }, + 3000, + ticket.id + ); - await verifyMessage(sentMessage, ticket, contact); + debouncedSentMessage(); } };