@dazejs/framework
Version:
Daze.js - A powerful web framework for Node.js
370 lines • 12 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Response = void 0;
const cache_content_type_1 = __importDefault(require("cache-content-type"));
const compressible_1 = __importDefault(require("compressible"));
const content_disposition_1 = __importDefault(require("content-disposition"));
const path_1 = require("path");
const stream_1 = require("stream");
const zlib = __importStar(require("zlib"));
const container_1 = require("../../container");
const cookie_1 = require("../cookie");
const resource_1 = require("../../resource/resource");
const view_1 = require("../../view");
const factory_1 = require("../../view/factory");
const statusable_1 = require("./statusable");
const pagination_1 = require("../../pagination");
const str_1 = require("../../utils/str");
const encodingMethods = {
gzip: zlib.createGzip,
deflate: zlib.createDeflate
};
const defaultContentTypes = {
JSON: 'application/json; charset=utf-8',
PLAIN: 'text/plain; charset=utf-8',
OCTET: 'application/octet-stream'
};
class Response extends statusable_1.Statusable {
constructor(data, code = 200, header = {}) {
super();
this.app = container_1.Container.get('app');
this.cookies = [];
this._isForce = false;
this._needEncrypt = false;
this._code = code;
this._header = this.parseHeaders(header);
this.setData(data);
}
set code(code) {
this.setCode(code);
}
get code() {
return this._code;
}
set data(data) {
this.setData(data);
}
get data() {
return this._data;
}
force() {
this._isForce = true;
return this;
}
isForce() {
return this._isForce;
}
parseHeaders(headers) {
const keys = Object.keys(headers);
const _headers = {};
for (const key of keys) {
_headers[key.toLocaleLowerCase()] = headers[key];
}
return _headers;
}
error(message, code = 404) {
this.setCode(code);
this.setData(message);
return this;
}
success(data, code = 200) {
this.setCode(code);
this.setData(data);
return this;
}
getHeader(name) {
return this._header[name.toLowerCase()];
}
setHeader(name, value) {
this._header[name.toLowerCase()] = value;
return this;
}
removeHeader(name) {
delete this._header[name.toLowerCase()];
return this;
}
getHeaders() {
return this._header;
}
setHeaders(headers) {
const keys = Object.keys(headers);
for (const key of keys) {
this.setHeader(key.toLowerCase(), headers[key]);
}
return this;
}
getCode() {
return this.code;
}
getStatus() {
return this.getCode();
}
setCode(code = 200) {
if (code)
this._code = code;
return this;
}
setStatus(code) {
return this.setCode(code);
}
getData() {
return this._data;
}
setType(type) {
const _type = (0, cache_content_type_1.default)(type);
if (_type) {
this.setHeader('Content-Type', _type);
}
return this;
}
getType() {
const type = this.getHeader('Content-Type');
if (!type)
return '';
return type.split(';', 1)[0];
}
setLength(length) {
this.setHeader('Content-Length', length);
return this;
}
getLength() {
const length = this.getHeader('Content-Length');
return length ? parseInt(length, 10) : 0;
}
setVary(field) {
const varyHeader = this.getHeader('Vary') || '';
const varys = String(varyHeader).split(',');
varys.push(field);
this.setHeader('Vary', varys.filter((v) => !!v).join(','));
}
lastModified(time) {
if (time instanceof Date) {
this.setHeader('Last-Modified', time.toUTCString());
return this;
}
if (typeof time === 'string' || typeof time === 'number') {
this.setHeader('Last-Modified', (new Date(time)).toUTCString());
return this;
}
return this;
}
expires(time) {
this.setHeader('Expires', time);
return this;
}
eTag(eTag) {
if (!(/^(W\/)?"/.test(eTag))) {
this.setHeader('ETag', `"${eTag}"`);
return this;
}
this.setHeader('ETag', eTag);
return this;
}
cacheControl(cache) {
this.setHeader('Cache-Control', cache);
return this;
}
noCache() {
this.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
this.setHeader('Pragma', 'no-cache');
return this;
}
contentType(contentType, charset = 'utf-8') {
this.setHeader('Content-Type', `${contentType}; charset=${charset}`);
return this;
}
attachment(filename = '', options) {
if (filename)
this.setType((0, path_1.extname)(filename));
this.setHeader('Content-Disposition', (0, content_disposition_1.default)(filename, options));
return this;
}
download(data, filename = '', options) {
return this.setData(data).attachment(filename, options);
}
transformData(request) {
const data = this.getData();
if (!data)
return data;
if (data instanceof resource_1.Resource) {
this.setType('json');
return data.output();
}
if (data instanceof view_1.View) {
this.setType('html');
return (new factory_1.ViewFactory(data)).output(request);
}
if (data instanceof pagination_1.Paginator) {
this.setType('json');
return data.toJSON();
}
return data;
}
withCookie(_cookie) {
if (_cookie instanceof cookie_1.Cookie) {
this.cookies.push(_cookie);
}
return this;
}
cookie(key, value, options = {}) {
this.withCookie(new cookie_1.Cookie(key, value, options));
return this;
}
json(data) {
this.setType('json');
if (data)
this.setData(data);
return this;
}
html(data) {
this.setType('html');
if (data)
this.setData(data);
return this;
}
text(data) {
this.setType('text');
if (data)
this.setData(data);
return this;
}
async commitCookies(request) {
for (const _cookie of this.cookies) {
request.cookies.set(_cookie.getName(), _cookie.getValue(), _cookie.getOptions());
}
if (this.app.needsSession) {
await request.session().autoCommit();
}
}
sendHeaders(res) {
if (res.headersSent)
return this;
const code = this.getCode();
const headers = this.getHeaders();
res.writeHead(code, headers);
return this;
}
setData(data) {
this._data = data;
return this;
}
encrypt(encrypt = true) {
this._needEncrypt = encrypt;
return this;
}
prepare(request) {
let data = this.transformData(request);
if (this._needEncrypt || request.needEncrypt) {
const config = this.app.get('config');
const key = config.get('app.key', 'dazejs');
const iv = config.get('app.iv', null);
data = str_1.Str.aesEncrypt(JSON.stringify(data), key, iv);
this.setHeader('encrypted', true);
this.setHeader('content-type', defaultContentTypes.PLAIN);
}
const shouldSetType = !this.getHeader('content-type');
if (data === null || typeof data === 'undefined') {
this.setCode(204);
this.removeHeader('content-type');
this.removeHeader('content-length');
this.removeHeader('transfer-encoding');
return data || '';
}
if (typeof data === 'string' || typeof data === 'number' || typeof data === 'boolean') {
if (shouldSetType)
this.setHeader('content-type', defaultContentTypes.PLAIN);
this.setHeader('content-length', Buffer.byteLength(data.toString()));
return data.toString();
}
if (Buffer.isBuffer(data)) {
if (shouldSetType)
this.setHeader('content-type', defaultContentTypes.OCTET);
this.setHeader('content-length', data.length);
return data;
}
if (typeof data.pipe === 'function') {
this.removeHeader('content-length');
if (shouldSetType)
this.setHeader('content-type', defaultContentTypes.OCTET);
return data;
}
this.removeHeader('content-length');
if (shouldSetType)
this.setHeader('content-type', defaultContentTypes.JSON);
return data;
}
async send(request) {
const data = this.prepare(request);
if (this.app.get('config').get('app.compress')) {
return this.endWithCompress(request, data);
}
return this.end(request, data);
}
async end(request, data) {
const { res } = request;
await this.commitCookies(request);
if (typeof data === 'string' || Buffer.isBuffer(data)) {
this.sendHeaders(res);
return res.end(data);
}
if (data instanceof stream_1.Stream) {
this.sendHeaders(res);
return data.pipe(res);
}
;
const jsonData = JSON.stringify(data);
if (!res.headersSent) {
this.setHeader('content-length', Buffer.byteLength(jsonData));
}
this.sendHeaders(res);
return res.end(jsonData);
}
endWithCompress(request, data) {
const encoding = request.acceptsEncodings('gzip', 'deflate', 'identity');
if (!encoding || encoding === 'identity')
return this.end(request, data);
if (!(0, compressible_1.default)(this.getType()))
return this.end(request, data);
const threshold = this.app.get('config').get('app.threshold', 1024);
if (threshold > this.getLength())
return this.end(request, data);
this.setHeader('Content-Encoding', encoding);
this.removeHeader('Content-Length');
const stream = encodingMethods[encoding]({});
if (data instanceof stream_1.Stream) {
data.pipe(stream);
}
else {
stream.end(data);
}
return this.end(request, stream);
}
}
exports.Response = Response;
//# sourceMappingURL=index.js.map