clonegur/backend/server/RestResponse.ts

57 lines
1.6 KiB
TypeScript
Raw Normal View History

2023-06-30 00:37:07 +00:00
import { lookup } from "https://deno.land/x/mrmime@v1.0.1/mod.ts"
2023-06-29 14:31:25 +00:00
import { stream } from "../utils/utils.ts";
import { Headers } from "./RestRequest.ts";
export default class RestResponse {
#status = 200;
#statusMsg = '';
#body?: ReadableStream<Uint8Array>;
headers: Headers = {};
public constructor() { }
public get statusCode() { return this.#status; }
public get statusMessage() { return this.#statusMsg; }
public get content() { return this.#body; }
2023-06-30 00:37:07 +00:00
public contentType(name: string) {
const res = lookup(name);
if (res) this.header('content-type', res);
return this;
}
2023-06-29 14:31:25 +00:00
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<Uint8Array>) {
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,
});
}
}