sw2express
Version:
A lite & simple cross-platform Express-like web application framework
129 lines (126 loc) • 3.26 kB
JavaScript
import headers from "./HTTPPage/Header.js";
export class nodeReply {
constructor(response, request, options) {
this.request = request;
this.response = response;
this.statusCode = 200;
this.headers = Object.assign({}, headers);
this.isSendHeader = false;
this.isEnd = false;
this.sendMsg = [];
this.options = options;
}
setHeader(name, value) {
this.headers[name] = value;
return this;
}
getHeader(name) {
return this.headers[name];
}
Nativesend(text) {
this.response.statusCode = this.statusCode;
for (let i in this.headers) {
this.response.setHeader(i, this.headers[i]);
}
this.isSendHeader = true;
this.response.write(text);
return this;
}
send(text) {
this.sendMsg.push(text);
this.MSG = this.sendMsg.join("");
}
async end(text) {
this.sendMsg.push(text);
this.MSG = this.sendMsg.join("");
if (this.options.ETag) {
const ETag = `W/"${await globalThis.md5(this.MSG)}"`;
this.setHeader("ETag", ETag);
if (ETag === this.request.headers["if-none-match"]) {
this.statusCode = 304;
this.response.statusCode = this.statusCode;
this.response.end("");
return true;
} else {
this.Nativeend(this.MSG);
}
return true;
}
this.Nativeend(this.MSG);
return true;
}
json(text) {
if (this.getHeader("Content-Type") === "text/plain; charset=utf-8") {
this.setHeader("Content-Type", "application/json; charset=utf-8");
}
this.end(JSON.stringify(text));
return this;
}
Nativeend(text) {
if (!this.isSendHeader && text) this.Nativesend(text).Nativeend();
else this.response.end(text);
this.isEnd = true;
return true;
}
set(a, b) {
this[a] = b;
}
}
export class swReply {
constructor(request, options) {
//this.response = response;
this.request = request;
this.statusCode = 200;
this.headers = Object.assign({}, headers);
this.isSendHeader = false;
this.isEnd = false;
this.sendMsg = [];
this.options = options;
}
setHeader(name, value) {
this.headers[name] = value;
return this;
}
getHeader(name) {
return this.headers[name];
}
async GenResponse() {
if (this.options.ETag) {
const ETag = `W/"${await globalThis.md5(this.MSG)}"`;
this.headers.ETag = ETag;
this.requestHeaders = Object.fromEntries(this.request.headers.entries());
if (ETag === this.requestHeaders["if-none-match"]) {
return new Response(null, {
headers: this.headers,
status: 304,
});
}
}
this.isSendHeader = true;
return new Response(this.MSG, {
headers: this.headers,
status: this.statusCode,
});
}
send(text) {
this.sendMsg.push(text);
this.MSG = this.sendMsg.join("");
return this;
}
json(text) {
if (this.getHeader("Content-Type") === "text/plain; charset=utf-8") {
this.setHeader("Content-Type", "application/json; charset=utf-8");
}
this.end(JSON.stringify(text));
return this;
}
end(text) {
this.sendMsg.push(text);
this.MSG = this.sendMsg.join("");
this.isEnd = true;
return this;
}
set(a, b) {
this[a] = b;
}
}