All files response-end-overrider.ts

100% Statements 15/15
100% Branches 1/1
100% Functions 4/4
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28            1x 2x 2x 2x   2x 2x 2x     2x 2x 1x     2x 2x   2x      
import { Response } from 'express';
/**
 * this function will override before response end
 * @param res Express Response
 * @param overrideFn Override Function that trigger before res.end
 */
export const responseEndOverrider = (res: Response, overrideFn: (resBody: string) => void) => {
  const defEnd = res.end;
  const defWrite = res.write;
  const chunks: Buffer[] = [];
 
  res.write = ((...args: any): void => {
    chunks.push(Buffer.from(args[0]));
    defWrite.apply(res, args);
  }) as any;
 
  res.end = (async (...args: any): Promise<void> => {
    if (args[0]) {
      chunks.push(Buffer.from(args[0]));
    }
 
    const resBody = Buffer.concat(chunks).toString('utf8');
    await overrideFn(resBody);
 
    defEnd.apply(res, args);
  }) as any;
};