import { STATUS_CODES } from 'http'; import { ServerResponse } from '../../types'; import { RootHandler } from './RootHandler'; import { JSONStringify } from '../../lib'; export const augmentResponse = (res: ServerResponse, rootHandler: RootHandler) => { res.json = json(res); res.send = sendType(res); res.sendError = sendError(res); }; const json = (res: ServerResponse) => ( data: object, code?: number, headers?: { [name: string]: string | number }, replacer?: (key: string, value: any) => any, spaces?: string | number, escape?: boolean ) => { sendType(res, replacer, spaces, escape)(data, code, headers); }; const sendError = (res: ServerResponse) => (code: number, data: any, headers?: { [name: string]: string | number }) => { sendType(res)(data, code, headers); }; const SEND_TYPE = 'Content-Type'; const SEND_OSTREAM = 'application/octet-stream'; const sendType = ( res: ServerResponse, replacer?: (key: string, value: any) => any, spaces?: string | number, escape?: boolean ) => (data: any = '', code = 200, headers: { [name: string]: string | number } = {}) => { let type = headers[SEND_TYPE]; if (!!data && typeof data.pipe === 'function') { res.setHeader(SEND_TYPE, type || SEND_OSTREAM); return data.pipe(res); } if (data instanceof Buffer) { type = type || SEND_OSTREAM; // prefer given } else if (typeof data === 'object') { const tmp = JSONStringify; data = JSONStringify(data, replacer, spaces, escape); type = 'application/json;charset=utf-8'; } else { data = data || STATUS_CODES[code]; } headers[SEND_TYPE] = type || 'text/plain'; headers['Content-Length'] = Buffer.byteLength(data); res.writeHead(code, headers); res.end(data); }; const send = (res: ServerResponse) => ( data: any = '', code = 200, headers: { [name: string]: string | number } = {} ) => { res.writeHead(code, headers); res.end(data || STATUS_CODES[code]); };