@curveball/kernel
Version:
Curveball is a framework writting in Typescript for Node.js
77 lines • 2.37 kB
JavaScript
import { Readable } from 'node:stream';
import { Headers } from './headers.js';
import { Request } from './request.js';
export class MemoryRequest extends Request {
/**
* List of HTTP Headers
*/
headers;
/**
* Contains a parsed, stored representation of the body. It's up to
* middlewares to do the actual parsing.
*/
body;
constructor(method, requestTarget, origin, headers, body = null, absoluteUrl) {
super(method, requestTarget, origin);
if (headers?.get !== undefined) {
this.headers = headers;
}
else {
this.headers = new Headers(headers);
}
this.originalBody = body;
// @ts-expect-error Typescript doesn't like null here because it might be
// incompatible with T, but we're ignoring it as it's a good default.
this.body = null;
}
/**
* Internal representation of body.
*
* We keep a private copy so we can maintain compatibility with rawBody.
*/
originalBody;
async rawBody(encoding, limit) {
return this.getBody(encoding);
}
/**
* getStream returns a Node.js readable stream.
*
* A stream can typically only be read once.
*/
getStream() {
const s = new Readable();
s.push(this.getBody());
s.push(null);
return s;
}
getBody(encoding) {
if (!this.originalBody) {
// Memoizing the null case
this.originalBody = '';
}
if (typeof this.originalBody === 'object' && !(this.originalBody instanceof Buffer)) {
// Memoizing the JSON object case.
this.originalBody = JSON.stringify(this.originalBody, null, 2);
}
if (this.originalBody instanceof Buffer) {
// The buffer case
if (typeof encoding === 'undefined') {
return this.originalBody;
}
else {
return this.originalBody.toString(encoding);
}
}
else {
// The string case
if (typeof encoding === 'undefined') {
return Buffer.from(this.originalBody);
}
else {
return this.originalBody;
}
}
}
}
export default MemoryRequest;
//# sourceMappingURL=memory-request.js.map