import { contentType, Status } from "./deps.ts";import { isHtml } from "./util.ts";
interface ServerResponse { status?: number; headers?: Headers; body?: Uint8Array;}
const BODY_TYPES = ["string", "number", "bigint", "boolean", "symbol"];
const encoder = new TextEncoder();
export class Response { private _getBody(): Uint8Array | undefined { const typeofBody = typeof this.body; let result: Uint8Array | undefined; if (BODY_TYPES.includes(typeofBody)) { const bodyText = String(this.body); result = encoder.encode(bodyText); this.type = this.type || (isHtml(bodyText) ? "html" : "text/plain"); } else if (this.body instanceof Uint8Array) { result = this.body; } else if (typeofBody === "object" && this.body !== null) { result = encoder.encode(JSON.stringify(this.body)); this.type = this.type || "json"; } return result; }
private _setContentType() { if (this.type) { const contentTypeString = contentType(this.type); if (contentTypeString && !this.headers.has("Content-Type")) { this.headers.append("Content-Type", contentTypeString); } } }
body?: any;
headers = new Headers();
status?: Status;
type?: string;
toServerResponse(): ServerResponse { const body = this._getBody();
this._setContentType();
if ( !( body || this.headers.has("Content-Type") || this.headers.has("Content-Length") ) ) { this.headers.append("Content-Length", "0"); }
return { status: this.status || (body ? Status.OK : Status.NotFound), body, headers: this.headers }; }}