import { lookup } from "https://deno.land/x/mrmime@v1.0.1/mod.ts" import { stream } from "../utils/utils.ts"; import { Headers } from "./RestRequest.ts"; export default class RestResponse { #status = 200; #statusMsg = ''; #body?: ReadableStream; headers: Headers = {}; public constructor() { } public get statusCode() { return this.#status; } public get statusMessage() { return this.#statusMsg; } public get content() { return this.#body; } public contentType(name: string) { const res = lookup(name); if (res) this.header('content-type', res); return this; } public header(name: string, val: string | string[]) { this.headers[name] = val; return this; } public status(val: number, message = '') { this.#status = val; this.#statusMsg = message; return this; } public body(val: string | ReadableStream) { if (typeof val === 'string') val = stream(val); this.#body = val; return this; } public toFetchResponse(): Response { const headers: string[][] = []; for (const key in this.headers) { const val = this.headers[key]; if (typeof val === 'string') { headers.push([key, val]); } else if (val instanceof Array) { headers.push([key, ...val]); } else headers.push([key]); } return new Response(this.#body, { headers: headers, status: this.#status, statusText: this.#statusMsg, }); } }