UNPKG

@dazejs/framework

Version:

Daze.js - A powerful web framework for Node.js

443 lines 12.4 kB
"use strict"; 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.Request = void 0; const accepts_1 = __importDefault(require("accepts")); const cookies_1 = __importDefault(require("cookies")); const parseurl_1 = __importDefault(require("parseurl")); const qs = __importStar(require("querystring")); const type_is_1 = require("type-is"); const url_1 = require("url"); const uuid_1 = require("uuid"); const container_1 = require("../../container"); const validate_http_error_1 = require("../../errors/validate-http-error"); const validate_1 = require("../../validate"); const session_1 = require("../session"); const parse_body_1 = require("./utils/parse-body"); class Request { constructor(req, res) { this.app = container_1.Container.get('app'); this._uuid = (0, uuid_1.v1)(); this._req = req; this._res = res; this._originUrl = this.url; return new Proxy(this, this.proxy()); } proxy() { return { get(t, prop, receiver) { if (Reflect.has(t, prop) || typeof prop !== 'string') { return Reflect.get(t, prop, receiver); } return t.getParam(prop); }, }; } async initialize(route) { this._route = route; if (this.app.needsParseBody) { this._body = await (0, parse_body_1.parseBody)(this); } if (this.app.needsSession) { await this.session().loadSession(); } } getUUID() { return this._uuid; } get req() { return this._req; } get res() { return this._res; } getReq() { return this._req; } getRes() { return this._res; } get body() { var _a, _b; return (_b = (_a = this._body) === null || _a === void 0 ? void 0 : _a.fields) !== null && _b !== void 0 ? _b : {}; } getBody() { return this.body; } get routeParams() { var _a; return (_a = this._route) === null || _a === void 0 ? void 0 : _a.getParams(this.path); } getRouteParams() { return this.routeParams; } get files() { return this._body && this._body.files || []; } getFiles() { return this.files; } get isHttp2() { return this._req.httpVersionMajor >= 2; } get header() { return this._req.headers; } get headers() { return this._req.headers; } set headers(val) { this._req.headers = val; } setHeaders(val) { this.headers = Object.assign(Object.assign({}, this.headers), val); return this; } get url() { var _a; return (_a = this._req.url) !== null && _a !== void 0 ? _a : ''; } set url(val) { this._req.url = val; } get originUrl() { return this._originUrl || ''; } getUrl() { return this.url; } setUrl(val) { this.url = val; return this; } get origin() { return `${this.protocol}://${this.host}`; } getOrigin() { return this.origin; } get href() { if (this.url && /^https?:\/\//i.test(this.url)) return this.url; return this.origin + this.url; } getHref() { return this.href; } get method() { return this._req.method; } getMethod() { return this.method; } get path() { const parsedReq = (0, parseurl_1.default)(this._req); return parsedReq && parsedReq.pathname || ''; } getPath() { return this.path; } get query() { const str = this.querystring; return qs.parse(str); } getQuery(name) { if (!name) return this.query; return this.query[name]; } get querystring() { const parsedReq = (0, parseurl_1.default)(this._req); return parsedReq && parsedReq.query || ''; } getQuerystring() { return this.querystring; } get search() { if (!this.querystring) return ''; return `?${this.querystring}`; } getSearch() { return this.search; } get host() { let host; const proxy = this.app.get('config').get('app.proxy'); if (proxy) host = this.getHeader('X-Forwarded-Host'); if (!host) { if (this.isHttp2) host = this.getHeader(':authority'); if (!host) host = this.getHeader('Host'); } return host ? host.split(/\s*,\s*/, 1)[0] : ''; } getHost() { return this.host; } get hostname() { var _a, _b; const host = this.host; if (!host) return ''; if (host[0] === '[') return (_b = (_a = this.URL) === null || _a === void 0 ? void 0 : _a.hostname) !== null && _b !== void 0 ? _b : ''; return host.split(':', 1)[0]; } getHostname() { return this.hostname; } get URL() { if (this._cachedURL) return this._cachedURL; try { this._cachedURL = new url_1.URL(`${this.origin}${this.url}`); } catch (err) { this._cachedURL = Object.create(null); } return this._cachedURL; } getURL() { return this.URL; } get socket() { return this._req.socket; } getSocket() { return this.socket; } get length() { const len = this.getHeader('Content-Length'); if (!len) return undefined; return Number(len) | 0; } getLength() { return this.length; } get protocol() { if (this.socket.encrypted) return 'https'; const proxy = this.app.get('config').get('app.proxy'); if (!proxy) return 'http'; const xForwordedProto = this.getHeader('X-Forwarded-Proto'); return xForwordedProto ? xForwordedProto.split(/\s*,\s*/, 1)[0] : 'http'; } getProtocol() { return this.protocol; } get secure() { return this.protocol === 'https'; } getSecure() { return this.secure; } get ips() { const proxy = this.app.get('config').get('app.proxy'); if (proxy) { const ips = this.getHeader('X-Forwarded-For'); return ips.split(/\s*,\s*/); } return []; } getIps() { return this.ips; } get ip() { return this.getIps()[0] || this.getSocket().remoteAddress || ''; } getIp() { return this.ip; } get accept() { return this._accepts || (this._accepts = (0, accepts_1.default)(this._req)); } getAccept() { return this.accept; } accepts(...params) { return this.acceptsTypes(...params); } acceptsTypes(...params) { return this.accept.types(...params); } acceptsEncodings(...params) { return this.accept.encodings(...params); } acceptsCharsets(...params) { return this.accept.charsets(...params); } acceptsLanguages(...params) { return this.accept.languages(...params); } is(...types) { return (0, type_is_1.is)(this.getHeader('content-type'), types); } get(name) { if (!name) return ''; const field = name.toLowerCase(); switch (field) { case 'referer': case 'referrer': return this._req.headers.referrer || this._req.headers.referer || ''; default: return this._req.headers[field] || ''; } } getHeader(field) { return this.get(field); } getHeaders() { return this.headers; } get type() { const type = this.getHeader('Content-Type'); if (!type) return ''; return type.split(';')[0]; } getType() { return this.type; } get cookies() { if (!this._cookies) { this._cookies = new cookies_1.default(this._req, this._res, { keys: this.app.keys, secure: this.secure, }); } return this._cookies; } cookieValue(key, options) { return this.cookies.get(key, options); } session() { if (!this._session) { this._session = new session_1.Session(this); } return this._session; } sessionValue(key) { return this.session().get(key); } get isAjax() { const x = this.headers['x-requested-with']; if (x && x.toLowerCase() === 'xmlhttprequest') { return true; } return false; } isOptions() { return this.method === 'OPTIONS'; } isHead() { return this.method === 'HEAD'; } isGet() { return this.method === 'GET'; } isPost() { return this.method === 'POST'; } isPut() { return this.method === 'PUT'; } isPatch() { return this.method === 'PATCH'; } isDelete() { return this.method === 'DELETE'; } get mergedParams() { if (!this._params) { if (typeof this.body === 'string') { this._params = Object.assign(Object.assign({}, this.query), { body: this.body }); } else { this._params = Object.assign(Object.assign({}, this.query), this.body); } } return this._params; } getParam(name, defaultValue) { if (!name) return undefined; return this.hasParam(name) ? this.mergedParams[name] : defaultValue; } getParams() { return this.mergedParams; } only(...args) { const res = {}; for (const arg of args) { if (typeof arg === 'string') { if (this.hasParam(arg)) { res[arg] = this.getParam(arg); } } else if (Array.isArray(arg)) { for (const name of arg) { if (this.hasParam(name)) { res[name] = this.getParam(name); } } } } return res; } except(...args) { let exceptKeys = []; let keys = Object.keys(this.mergedParams); for (const arg of args) { if (typeof arg === 'string') { exceptKeys.push(arg); } else if (Array.isArray(arg)) { exceptKeys = exceptKeys.concat(arg); } } keys = keys.filter(key => !~exceptKeys.indexOf(key)); return this.only(keys); } hasParam(name) { return Reflect.has(this.mergedParams, name); } validate(validator, message = 'Validation error') { const validate = new validate_1.Validate(validator); if (!validate.check(this.mergedParams)) { throw new validate_http_error_1.ValidateHttpError(message, validate); } } } exports.Request = Request; //# sourceMappingURL=index.js.map