From 1d4ce8345cb8d184b1bbe4eed29dac276ca2ac1d Mon Sep 17 00:00:00 2001 From: Ruslan Lopatin Date: Thu, 15 Oct 2020 11:33:37 +0700 Subject: [PATCH] Prevent previous request processing result to affect the next request --- src/http/http-listener.ts | 52 +++++++++++++++++++++------------------ 1 file changed, 28 insertions(+), 24 deletions(-) diff --git a/src/http/http-listener.ts b/src/http/http-listener.ts index ba7191d..45e60e8 100644 --- a/src/http/http-listener.ts +++ b/src/http/http-listener.ts @@ -100,27 +100,37 @@ export function httpListener>({ handler: incomingHandler, - next(handler, context): Promise { + next( + handler, + context, + ): Promise { const { response } = context; - return Promise.race([ - whenResponded, - Promise.resolve(context) - .then(handler) - .then(() => response.writableEnded), - ]); + return Promise.resolve(context) + .then(handler) + .then(() => response.writableEnded); }, }); return (request: TRequest, response: TResponse): void => { - processor({ request, response, log }) - .catch( - error => log.error(`[${request.method} ${request.url}]`, 'Unhandled error', error), - ); + new Promise((onResponse, onError) => { + processor({ + request, + response, + log, + onResponse, + onError, + }).then( + onResponse, + onError, + ); + }).catch(error => { + log.error(`[${request.method} ${request.url}]`, 'Unhandled error', error); + }); }; } @@ -131,6 +141,8 @@ interface IncomingHttpMeans( handler: RequestHandler>, -): [RequestHandler>, Promise] { - - let onResponse: () => void; - let onError: (error: any) => void; - const whenResponded = new Promise((resolve, reject) => { - onResponse = () => resolve(true); - onError = reject; - }); - - const incomingHandler: RequestHandler> = ({ +): RequestHandler> { + return ({ request, response, next, + onResponse, + onError, }) => { response.once('error', onError); response.once('finish', onResponse); @@ -187,8 +193,6 @@ function incomingHttpHandler