Created
September 12, 2022 09:19
-
-
Save igrek8/1dbac323159419b71e58c479eb392bf3 to your computer and use it in GitHub Desktop.
Reads express.js response
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Response } from "express"; | |
type WriteCallback = (error: Error | null | undefined) => void; | |
type WriteArguments1 = [chunk: any, callback?: WriteCallback]; | |
type WriteArguments2 = [chunk: any, encoding: BufferEncoding, callback?: (error: Error | null | undefined) => void]; | |
type EndCallback = () => void; | |
type EndParameters1 = [cb?: EndCallback]; | |
type EndParameters2 = [chunk: any, cb?: EndCallback]; | |
type EndParameters3 = [chunk: any, encoding: BufferEncoding, cb?: EndCallback]; | |
export function collectResponseBody(res: Response): Promise<Buffer> { | |
return new Promise<Buffer>((resolve, reject) => { | |
const chunks: Buffer[] = []; | |
const _write = res.write.bind(res); | |
const _end = res.end.bind(res); | |
res.write = function write(...args: WriteArguments1 | WriteArguments2) { | |
const chunk = args[0]; | |
const encoding = args[1]; | |
const callback = args[2]; | |
return typeof encoding === "object" ? _write(chunk, encoding, callback) : _write(chunk, callback); | |
}; | |
res.end = function end(...args: EndParameters1 | EndParameters2 | EndParameters3) { | |
const chunk = args[0]; | |
const encoding = args[1]; | |
const callback = args[2]; | |
if (chunk) chunks.push(chunk); | |
return typeof encoding === "object" ? _end(chunk, encoding, callback) : _end(chunk, callback); | |
}; | |
res.once("error", (error) => reject(error)); | |
res.once("close", () => resolve(Buffer.concat(chunks))); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment