@sigiljs/sigil
Version:
TypeScript-first Node.js HTTP framework offering schema-driven routing, modifier-based middleware, plugin extensibility, and flexible response templating
73 lines (72 loc) • 2.13 kB
JavaScript
import { jsonStringify as i, jsonParse as r } from "../../utils/safe-json.mjs";
class h {
/** Size of the body in bytes. */
size;
/** Internal buffer storing raw body data. */
#t;
#i;
#r;
#s;
#e;
/**
* Constructs an IncomingBody instance.
*
* @param buffer original body content. Can be a Buffer, string, object, or null.
* Objects will be converted into strings.
*/
constructor(t) {
this.#t = t instanceof Buffer ? t : Buffer.from(i(t, { throw: !0 })), this.size = this.#t.length;
}
/**
* Parses and returns the body as JSON.
* Caches parsed value for future calls.
*
* @template T type to parse into when `Json` generic is not a record.
* @template N whether the result should be non-nullable.
* @template R resolved return type based on `Json` and `T`.
* @param nonNullable if `true`, enforces non-nullability in parsing.
* @returns parsed JSON of type `R` or `null` if parsing fails and `nonNullable` is `false`.
*/
json(t) {
return this.#i !== void 0 ? this.#i : (this.#i = r(this.text(), t), this.#i);
}
/**
* Returns the body decoded as a UTF-8 string.
* Caches the result for future calls.
*
* @returns body text.
*/
text() {
return this.#r !== void 0 ? this.#r : (this.#r = this.#t.toString("utf8"), this.#r);
}
/**
* Returns the raw Buffer of the body.
*
* @returns body Buffer.
*/
buffer() {
return this.#t;
}
/**
* Returns the body as a Blob with the specified MIME type.
* Caches the result for future calls.
*
* @param mimeType MIME type for the Blob (e.g., "application/json").
* @returns blob representing the body.
*/
blob(t) {
return this.#s !== void 0 ? this.#s : (this.#s = new Blob([this.#t], { type: t }), this.#s);
}
/**
* Parses the body as URL search parameters.
* Caches the result for future calls.
*
* @returns URLSearchParams instance built from the body string.
*/
urlSearchParams() {
return this.#e !== void 0 ? this.#e : (this.#e = new URLSearchParams(this.#t.toString("utf8")), this.#e);
}
}
export {
h as default
};