From 0c7705f36a1cd2bee8dad8ff6d02dc624afdf563 Mon Sep 17 00:00:00 2001 From: Oj Date: Fri, 24 Dec 2021 13:02:28 +0000 Subject: [PATCH] [Polyfill > Request] Fix not returning self after on(), rewrite to use optional chaining not ifs --- polyfills/request.js | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/polyfills/request.js b/polyfills/request.js index 97f919d..fa99650 100644 --- a/polyfills/request.js +++ b/polyfills/request.js @@ -54,30 +54,35 @@ const request = (options, callback) => { // Main function const isError = !res.agent; if (isError) { - if (listeners['error']) listeners['error'](res); - if (callback) callback(res, null, null); // Return null for others? + listeners['error']?.(res); + callback?.(res, null, null); // Return null for others? return; } - if (listeners['response']) listeners['response'](res); - if (!callback) return; + listeners['response']?.(res); let body = ''; res.setEncoding('utf8'); - res.on('data', (chunk) => body += chunk); + res.on('data', (chunk) => { + body += chunk; + listeners['data']?.(chunk); + }); await new Promise((resolve) => res.on('end', resolve)); // Wait to read full body - callback(undefined, res, body); + callback?.(undefined, res, body); }); - return { + const ret = { on: (type, handler) => { listeners[type] = handler; + return ret; // Return self } - } + }; + + return ret; }; // Method functions