UNPKG

xmt-base

Version:

Backend Server Framework of XmT Inc.

97 lines 3.42 kB
"use strict"; const etag = require("etag"); const fresh = require("fresh"); exports.responseProto = { xmt_setHeader: function (keyValuePair) { for (let key of Object.keys(keyValuePair)) { let value = keyValuePair[key]; if (key.toLowerCase() === "content-type") { switch (value) { case "json": value = "application/json; charset=utf-8"; break; case "html": value = "text/html; charset=utf-8"; break; case "text": value = "text/plain; charset=utf-8"; break; case "bin": value = "application/octet-stream"; break; } } this.setHeader(key, value); } return this; }, xmt_setStatus: function (code) { this.statusCode = code; return this; }, xmt_send: function (body) { if (this.finished) { return this; } if (!body) { this.end(); return this; } else { let chunk = body; let contentType = this.getHeader("Content-Type"); let encoding = "utf8"; let length; switch (typeof chunk) { case "string": if (!contentType) { this.xmt_setHeader({ "Content-Type": "text" }); } break; case "object": if (Buffer.isBuffer(chunk)) { if (!contentType) { this.xmt_setHeader({ "Content-Type": "bin" }); } } else { if (!contentType) { this.xmt_setHeader({ "Content-Type": "json" }); } chunk = JSON.stringify(chunk, null, 4); } break; } if (chunk) { if (!Buffer.isBuffer(chunk)) { chunk = new Buffer(chunk, encoding); } length = chunk.length; this.xmt_setHeader({ "Content-Length": length }); } if (!this.getHeader("etag") && length) { let generatedEtag = etag(chunk, { weak: true }); if (generatedEtag) { this.xmt_setHeader({ "ETag": generatedEtag }); } } let freshness = fresh(this.xmt_request, this); if (freshness) this.statusCode = 304; if (this.statusCode === 204 || this.statusCode === 304) { this.removeHeader("Content-Type"); this.removeHeader("Content-Length"); this.removeHeader("Transfer-Encoding"); chunk = ''; } if (this.xmt_request.method === "HEAD") { this.end(); } else { this.end(chunk, encoding); } } return this; } }; //# sourceMappingURL=response.js.map