import {Response, StatusCode} from "../types"; /** * Writes the response status and data to the response. * and closes the response. */ export async function completeResponse(res: Response, code: StatusCode, data: string | null): Promise { res.status(code); res.appendHeader("Cache-Control", "no-cache"); res.appendHeader("X-Content-Type-Options", "nosniff"); if (data === undefined) { console.log("data is undefined"); } if (data !== null) { res.appendHeader("Content-Length", data.length.toString()); await res.write(data); } await res.close(); } /** * Write JSON flushes the given data object as JSON to the response * and closes the response. */ export function writeJSON(res: Response, code: StatusCode, data: unknown): Promise { const content = data === undefined ? "null" : JSON.stringify(data, null, 2); res.appendHeader("Content-Type", "application/json"); return completeResponse(res, code, content); } export function writeError(res: Response, code: StatusCode, err: Error) { return writeJSON(res, code, { code, message: err.message, details: null, }); }