kequapp
Version:
A minimal, zero-magic Node web framework built on native APIs
91 lines (90 loc) • 2.63 kB
JavaScript
/** biome-ignore-all lint/suspicious/noExplicitAny: too many possibilities */
import { STATUS_CODES } from 'node:http';
import { Transform } from 'node:stream';
export class FakeReq extends Transform {
method;
url;
headers;
rawHeaders;
constructor(options) {
super();
for (const key of Object.keys(options)) {
this[key] = options[key];
}
this.method = options.method ?? 'GET';
this.url = options.url ?? '';
this.headers = {};
this.rawHeaders = [];
if (options.headers) {
for (const key of Object.keys(options.headers)) {
if (options.headers[key] === undefined)
continue;
const value = options.headers[key];
this.headers[key.toLowerCase()] = value;
this.rawHeaders.push(key, value);
}
}
if (options.body !== null) {
this.end(options.body);
}
}
_transform(chunk, _enc, done) {
if (typeof chunk === 'string' || Buffer.isBuffer(chunk)) {
this.push(chunk);
}
else {
this.push(JSON.stringify(chunk));
}
done();
}
}
export class FakeRes extends Transform {
statusCode;
statusMessage;
_headers;
_responseData;
constructor() {
super();
this.statusCode = 200;
this.statusMessage = STATUS_CODES[this.statusCode] ?? 'OK';
this._headers = {};
this._responseData = [];
}
_transform(chunk, _enc, done) {
this.push(chunk);
this._responseData.push(chunk);
done();
}
setHeader(name, value) {
this._headers[name.toLowerCase()] = value;
}
getHeader(name) {
return this._headers[name.toLowerCase()];
}
getHeaders() {
return this._headers;
}
removeHeader(name) {
delete this._headers[name.toLowerCase()];
}
writeHead(statusCode, statusMessage, headers) {
if (statusMessage !== undefined && typeof statusMessage !== 'string') {
headers = statusMessage;
statusMessage = undefined;
}
this.statusCode = statusCode;
this.statusMessage =
statusMessage ?? STATUS_CODES[statusCode] ?? 'unknown';
if (!headers)
return;
for (const name of Object.keys(headers)) {
this.setHeader(name, headers[name]);
}
}
_getString() {
return Buffer.concat(this._responseData).toString();
}
_getJSON() {
return JSON.parse(this._getString());
}
}