diff --git a/src/abort-controller.middleware.ts b/src/abort-controller.middleware.ts index ca3fea2..b559aa0 100644 --- a/src/abort-controller.middleware.ts +++ b/src/abort-controller.middleware.ts @@ -27,13 +27,26 @@ export class AbortControllerMiddleware implements NestMiddleware { req.abortController = controller; req.abortSignal = controller.signal; - req.on('close', () => { + let requestFinished = false; + + res.on('close', () => { + if (requestFinished) { + return; + } + if (enableLogging) { this.logger.debug(LOG_MESSAGES.CLIENT_DISCONNECTED); } controller.abort(); }); + res.on('finish', () => { + requestFinished = true; + if (enableLogging) { + this.logger.debug(LOG_MESSAGES.REQUEST_COMPLETED); + } + }); + if (timeout > 0) { const timeoutId = setTimeout(() => { if (enableLogging) { @@ -42,16 +55,10 @@ export class AbortControllerMiddleware implements NestMiddleware { controller.abort(); }, timeout); - req.on('close', () => clearTimeout(timeoutId)); + res.on('close', () => clearTimeout(timeoutId)); res.on('finish', () => clearTimeout(timeoutId)); } - res.on('finish', () => { - if (enableLogging) { - this.logger.debug(LOG_MESSAGES.REQUEST_COMPLETED); - } - }); - next(); } }