UNPKG

@versatiles/server

Version:
70 lines (69 loc) 2.49 kB
import { brotli, gzip, unbrotli, ungzip } from './compressors.js'; import { logImportant } from './log.js'; export class Response { #response; constructor(response) { this.#response = response; } sendJSONString(json, config) { return this.sendContent({ buffer: Buffer.from(json), compression: 'raw', mime: 'application/json; charset=utf-8' }, config); } async sendContent(response, config) { const mime = response.mime ?? 'application/octet-stream'; let compression = response.compression ?? 'raw'; const { acceptGzip, acceptBr, optimalCompression } = config; let data = response.buffer; switch (compression) { case 'br': if (acceptBr) break; if (optimalCompression && acceptGzip) { data = await gzip(await unbrotli(data)); compression = 'gzip'; break; } data = await unbrotli(data); compression = 'raw'; break; case 'gzip': if (acceptGzip) break; if (optimalCompression && acceptBr) { data = await brotli(await ungzip(data)); compression = 'br'; break; } data = await ungzip(data); compression = 'raw'; break; default: // raw if (optimalCompression && acceptBr) { data = await brotli(data); compression = 'br'; break; } if (optimalCompression && acceptGzip) { data = await gzip(data); compression = 'gzip'; break; } compression = 'raw'; break; } if (compression !== 'raw') this.#response.setHeader('content-encoding', compression); this.#response.statusCode = 200; this.#response.setHeader('content-type', mime); this.#response.end(data); } sendError(err, code = 500) { logImportant(String(err)); this.#response.statusCode = code; this.#response.setHeader('content-type', 'text/plain'); this.#response.end((typeof err == 'string') ? err : 'internal error'); } }