@tsed/platform-http
Version:
A TypeScript Framework on top of Express
86 lines (85 loc) • 2.38 kB
JavaScript
import { EventEmitter } from "node:events";
import cookie from "cookie";
export class FakeResponse extends EventEmitter {
constructor(opts = {}) {
super();
this.headers = {};
this.locals = {};
this.statusCode = 200;
Object.assign(this, opts);
}
append(field, val) {
const prev = this.get(field);
let value = val;
if (prev) {
// concat the new and prev vals
value = Array.isArray(prev) ? prev.concat(val) : Array.isArray(val) ? [prev].concat(val) : [prev, val];
}
return this.set(field, value);
}
status(code) {
this.statusCode = code;
return this;
}
contentType(content) {
this.set("content-type", content);
}
contentLength(content) {
this.set("content-length", content);
}
cookie(name, value, options) {
const opts = { ...options };
const val = typeof value === "object" ? "j:" + JSON.stringify(value) : String(value);
if (opts.maxAge != null) {
const maxAge = opts.maxAge - 0;
if (!isNaN(maxAge)) {
opts.expires = new Date(Date.now() + maxAge);
opts.maxAge = Math.floor(maxAge / 1000);
}
}
if (opts.path == null) {
opts.path = "/";
}
this.append("Set-Cookie", cookie.serialize(name, String(val), opts));
return this;
}
clearCookie(name, options) {
const opts = { path: "/", ...options, expires: new Date(1) };
delete opts.maxAge;
return this.cookie(name, "", opts);
}
redirect(status, path) {
this.statusCode = status;
this.set("location", path);
}
location(path) {
this.set("location", path);
}
get(key) {
return this.headers[key.toLowerCase()];
}
getHeaders() {
return this.headers;
}
set(key, value) {
this.headers[key.toLowerCase()] = value;
return this;
}
setHeader(key, value) {
this.headers[key.toLowerCase()] = value;
return this;
}
send(data) {
this.data = data;
}
json(data) {
this.data = data;
}
write(chunk) {
this.emit("data", chunk);
}
end(data) {
data !== undefined && (this.data = data);
this.emit("end");
}
}