tezx
Version:
TezX is a modern, ultra-lightweight, and high-performance JavaScript framework built specifically for Bun. It provides a minimal yet powerful API, seamless environment management, and a high-concurrency HTTP engine for building fast, scalable web applicat
95 lines (94 loc) • 2.9 kB
JavaScript
import { url2query } from "../utils/url.js";
export class TezXRequest {
url;
method;
pathname;
#rawRequest;
params = {};
#bodyConsumed = false;
#rawBodyArrayBuffer;
#cachedText;
#cachedJSON;
#cachedFormObject;
#headersCache;
#queryCache;
constructor(req, method, pathname, params) {
this.url = req.url;
this.params = params ?? {};
this.method = method;
this.#rawRequest = req;
this.pathname = pathname ?? "/";
}
header(header) {
if (header) {
return this.#rawRequest.headers.get(header.toLowerCase());
}
if (this.#headersCache)
return this.#headersCache;
const obj = {};
this.#rawRequest.headers.forEach((value, key) => {
obj[key.toLowerCase()] = value;
});
this.#headersCache = obj;
return this.#headersCache;
}
get query() {
return (this.#queryCache ??= url2query(this.url));
}
async #ensureRawBuffer() {
if (this.#bodyConsumed)
return;
this.#rawBodyArrayBuffer = await this.#rawRequest.arrayBuffer();
this.#bodyConsumed = true;
}
async text() {
if (this.#cachedText !== undefined)
return this.#cachedText;
await this.#ensureRawBuffer();
this.#cachedText = new TextDecoder().decode(this.#rawBodyArrayBuffer);
return this.#cachedText;
}
get #contentType() {
const ct = this.#rawRequest.headers.get("content-type");
if (!ct)
return "";
return ct.split(";")[0].trim().toLowerCase();
}
async json() {
if (this.#cachedJSON !== undefined)
return this.#cachedJSON;
if (this.#contentType !== "application/json")
return {};
try {
if (!this.#bodyConsumed) {
this.#cachedJSON = await this.#rawRequest.json();
this.#bodyConsumed = true;
}
else {
const txt = await this.text();
this.#cachedJSON = txt ? JSON.parse(txt) : {};
}
}
catch {
this.#cachedJSON = {};
}
return this.#cachedJSON;
}
async formData() {
if (this.#cachedFormObject)
return this.#cachedFormObject;
const ct = this.#contentType;
if (!ct)
throw new Error("Missing Content-Type");
if (ct === "application/x-www-form-urlencoded" ||
ct === "multipart/form-data") {
if (this.#bodyConsumed) {
throw new Error("Multipart body already consumed elsewhere");
}
this.#cachedFormObject = (await this.#rawRequest.formData());
this.#bodyConsumed = true;
return this.#cachedFormObject;
}
return this.#cachedFormObject;
}
}