Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

vweb-mvc

Package Overview
Dependencies
Maintainers
1
Versions
137
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

vweb-mvc - npm Package Compare versions

Comparing version 1.0.83 to 1.1.1

lib/anno/index.d.ts

530

lib/anno/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _vwebCore = require("vweb-core");
var assert = _vwebCore.util.assert;
/**
* 视图控制器
* @param name 控制器名字 或者依赖
* @returns {set}
* @constructor
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.Response = exports.Param = exports.Validator = exports.Scope = exports.Filter = exports.Interceptor = exports.Delete = exports.Put = exports.Post = exports.Get = exports.Request = exports.Controller = void 0;
let { util, onlyClass, setAnnotation } = require('vweb-core');
const { assert } = util;
function Controller(name) {
var set = function set(target, property) {
(0, _vwebCore.onlyClass)(property);
var annotation = {
name: name || _vwebCore.util.uncapitalize(target.name),
type: 'controller',
component: true,
annType: Controller
const set = (target, property) => {
onlyClass(property);
let annotation = {
name: name || util.uncapitalize(target.name),
type: 'controller', component: true, annType: Controller
};
setAnnotation(target, annotation);
};
(0, _vwebCore.setAnnotation)(target, annotation);
};
if (name instanceof Function) {
var target = name;
name = null;
set(target, arguments[1]);
} else {
return set;
}
if (name instanceof Function) {
let target = name;
name = null;
set(target, arguments[1]);
}
else {
return set;
}
}
exports.Controller = Controller;
Controller.type = 'controller';
Controller.keys = ['name'];
var HTTP_METHODS = ['all', 'get', 'post', 'put', 'delete'];
/**
* 设置mapping
* @param func controller里面的方法
* @param httpMethod http请求的方法
* @param path http请求的路径
* @return {{mappings: {}}}
*/
var setMappings = function setMappings(func, httpMethod, path) {
var mappings = {};
mappings[func] = [];
var methods = [];
if (typeof httpMethod === "string") {
methods.push(httpMethod);
} else if (Array.isArray(httpMethod)) {
methods.push.apply(methods, (0, _toConsumableArray2["default"])(httpMethod));
} else {
throw new Error("Un support type ".concat((0, _typeof2["default"])(httpMethod)));
}
for (var _i = 0, _methods = methods; _i < _methods.length; _i++) {
var method = _methods[_i];
assert.isTrue(HTTP_METHODS.includes(method), "Unsupport method, only support ".concat(HTTP_METHODS.join(',')));
mappings[func].push({
value: path,
method: method
});
}
return {
mappings: mappings
};
const HTTP_METHODS = ['all', 'get', 'post', 'put', 'delete'];
const setMappings = (func, httpMethod, path) => {
let mappings = {};
mappings[func] = [];
let methods = [];
if (typeof httpMethod === "string") {
methods.push(httpMethod);
}
else if (Array.isArray(httpMethod)) {
methods.push(...httpMethod);
}
else {
throw new Error(`Un support type ${typeof httpMethod}`);
}
for (let method of methods) {
assert.isTrue(HTTP_METHODS.indexOf(method) !== -1, `Unsupport method, only support ${HTTP_METHODS.join(',')}`);
mappings[func].push({ value: path, method });
}
return { mappings };
};
/**
* 在类上 无参数 @RequestMapping 入参为 Function 无需返回值
* 在类上 有参数 @RequestMapping('/', 'get') 返回值应该为 function
* 在方法上 无参数 @RequestMapping 入参为object对象 注解设置在对象上
* 在方法上 有参数 @RequestMapping 返回值应该为function
*
* 监听路径请求标记
* eg:@RequestMapping('/')
* eg:@RequestMapping('/login/:key') 动态路径 key
* eg: @RequestMapping
* eg: @RequestMapping('/', 'get')
* eg: @RequestMapping('/', 'post')
* eg: @RequestMapping('/', 'put')
* eg: @RequestMapping('/', 'delete')
* @return {function(*=, *=): void}
*/
function RequestMapping() {
var path = arguments[0] || '',
method = arguments[1] || 'all';
var setDescriptor = function setDescriptor(target, property) {
return (0, _vwebCore.setAnnotation)(target, property ? setMappings(property, method, path) : {
mapping: {
value: path,
method: method
}
function Request() {
let path = arguments[0] || '', method = arguments[1] || 'all';
const setDescriptor = (target, property) => setAnnotation(target, property ? setMappings(property, method, path) : {
mapping: {
value: path,
method
}
});
};
if (arguments[0] instanceof Object || arguments[0] instanceof Function) {
// 注解在(方法|类)上且无参数
path = '';
method = 'all';
setDescriptor(arguments[0], arguments[1]);
} else {
// 注解在(类|方法)上有参数
return setDescriptor;
}
if (arguments[0] instanceof Object || arguments[0] instanceof Function) {
path = '';
method = 'all';
setDescriptor(arguments[0], arguments[1]);
}
else {
return setDescriptor;
}
}
RequestMapping.keys = ['mappings', 'mapping'];
var appointMapping = function appointMapping(method) {
return function () {
var path = arguments[0] || '';
var setDescriptor = function setDescriptor(target, property) {
return (0, _vwebCore.setAnnotation)(target, property ? setMappings(property, method, path) : {
mapping: {
value: path,
method: method
exports.Request = Request;
Request.keys = ['mappings', 'mapping'];
const appointMapping = method => {
return function () {
let path = arguments[0] || '';
const setDescriptor = (target, property) => setAnnotation(target, property ? setMappings(property, method, path) : {
mapping: {
value: path,
method
}
});
if (arguments[0] instanceof Object || arguments[0] instanceof Function) {
path = '';
setDescriptor(arguments[0], arguments[1]);
}
});
else {
return setDescriptor;
}
};
if (arguments[0] instanceof Object || arguments[0] instanceof Function) {
// 注解在(方法|类)上且无参数
path = '';
setDescriptor(arguments[0], arguments[1]);
} else {
// 注解在(类|方法)上有参数
return setDescriptor;
}
};
};
/**
* 监听get请求
* @GetMapping
* @GetMapping('/')
* @return {function(*=, *=): void}
* @constructor
*/
var GetMapping = appointMapping('get');
GetMapping.keys = ['mappings'];
/**
* post
* @PostMapping
* @PostMapping('/')
* @return {function(*=, *=): void}
* @constructor
*/
var PostMapping = appointMapping('post');
PostMapping.keys = ['mappings'];
/**
* put
* @PutMapping
* @PutMapping('/')
* @return {function(*=, *=): void}
* @constructor
*/
var PutMapping = appointMapping('put');
PutMapping.keys = ['mappings'];
/**
* put
* @DeleteMapping
* @DeleteMapping('/')
* @return {function(*=, *=): void}
* @constructor
*/
var DeleteMapping = appointMapping('delete');
DeleteMapping.keys = ['mappings'];
/**
* @deprecated 弃用 请使用@Filter FilterAdapter 替代
*
* @param path 需要拦截的路径 多个路径用“,”隔开
* @param {string | undefined} name 拦截器的名字 或者依赖对象
* @returns {Function}
* @constructor
*/
exports.Get = appointMapping('get');
exports.Get.keys = ['mappings'];
exports.Post = appointMapping('post');
exports.Post.keys = ['mappings'];
exports.Put = appointMapping('put');
exports.Put.keys = ['mappings'];
exports.Delete = appointMapping('delete');
exports.Delete.keys = ['mappings'];
function Interceptor(path, name) {
if (typeof path !== 'string') {
throw new Error("Interceptor ".concat(path.constructor.name, " must be set path"));
}
return function (target, property, descriptor) {
(0, _vwebCore.onlyClass)(property);
var annotation = {
name: name || _vwebCore.util.uncapitalize(target.name),
type: 'interceptor',
path: path,
component: true,
annType: Interceptor
if (typeof path !== 'string') {
throw new Error(`Interceptor ${path.constructor.name} must be set path`);
}
return (target, property, descriptor) => {
onlyClass(property);
let annotation = {
name: name || util.uncapitalize(target.name),
type: 'interceptor',
path,
component: true, annType: Interceptor
};
setAnnotation(target, annotation);
};
(0, _vwebCore.setAnnotation)(target, annotation);
};
}
exports.Interceptor = Interceptor;
Interceptor.type = 'interceptor';
Interceptor.keys = ['name', 'path'];
/**
*
* @param {string|RegExp} path 需要拦截的路径 支持正则表达式对象 RegExp 跟 /xxx/
* @param {name|undefined} name 拦截器的名字 或者依赖对象
* @returns {Function}
* @constructor
*/
function Filter(path, name) {
if (typeof path !== 'string' && !(path instanceof RegExp)) {
throw new Error("WebInterceptor ".concat(path.constructor.name, " must be set path"));
}
return function (target, property, descriptor) {
(0, _vwebCore.onlyClass)(property);
var annotation = {
name: name || _vwebCore.util.uncapitalize(target.name),
type: 'filter',
path: path,
component: true,
annType: Filter
if (typeof path !== 'string' && !(path instanceof RegExp)) {
throw new Error(`WebInterceptor ${path.constructor.name} must be set path`);
}
return (target, property, descriptor) => {
onlyClass(property);
let annotation = {
name: name || util.uncapitalize(target.name),
type: 'filter',
path,
component: true,
annType: Filter
};
setAnnotation(target, annotation);
};
(0, _vwebCore.setAnnotation)(target, annotation);
};
}
exports.Filter = Filter;
Filter.type = 'filter';
Filter.keys = ['name', 'path'];
/**
* 用于声明全局对象,可在页面上直接调用该对象的属性或者方法
* @param name 全局对象名字 $name 作为在页面视图调用的句柄
* @returns {Function}
* @constructor
*/
function AppScope(name) {
return function (target, property, descriptor) {
(0, _vwebCore.onlyClass)(property);
var annotation = {
name: name || _vwebCore.util.uncapitalize(target.name),
type: 'appScope',
component: true,
annType: AppScope
function Scope(name) {
return (target, property, descriptor) => {
onlyClass(property);
let annotation = {
name: name || util.uncapitalize(target.name),
type: 'appScope',
component: true, annType: Scope
};
setAnnotation(target, annotation);
};
(0, _vwebCore.setAnnotation)(target, annotation);
};
}
AppScope.type = 'appScope';
AppScope.keys = ['name'];
/**
*
* @param validator {name:{required: true, valid: function(){}, pattern: ''}}
* eg: @Validator({
aaa: function (val, param) {
console.log(this, val, param);
},
vvv: true,
ccc: "^[0-9]$",
ddd: /^[0-9]$/g,
eee: new RegExp("^[0-9]12$", "g")
})
* @constructor
*/
exports.Scope = Scope;
Scope.type = 'appScope';
Scope.keys = ['name'];
function Validator() {
var validator = arguments[0];
var setDecorator = function setDecorator(target, property, descriptor) {
assert.isTrue(property, 'Only set @Validator on method');
var validators = {};
descriptor.writable = false;
descriptor.configurable = false;
descriptor.enumerable = false;
validators[property] = validator;
(0, _vwebCore.setAnnotation)(target, {
validators: validators
});
};
if (arguments[1]) {
var target = validator;
validator = {
__all: true
let validator = arguments[0];
const setDecorator = (target, property, descriptor) => {
assert.isTrue(property, 'Only set @Validator on method');
let validators = {};
descriptor.writable = false;
descriptor.configurable = false;
descriptor.enumerable = false;
validators[property] = validator;
setAnnotation(target, { validators });
};
setDecorator(target, arguments[1], arguments[2]);
} else {
return setDecorator;
}
if (arguments[1]) {
let target = validator;
validator = { __all: true };
setDecorator(target, arguments[1], arguments[2]);
}
else {
return setDecorator;
}
}
exports.Validator = Validator;
Validator.keys = ["validator"];
/**
*
* @param discribe {validator:@ses @Validator, converter: {}}
* @returns {setDescriptor}
* @constructor
*/
function RequestParam(discribe) {
discribe = arguments[0];
var setDescriptor = function setDescriptor(target, property, descriptor) {
var _discribe = discribe,
validator = _discribe.validator,
converter = _discribe.converter;
Validator.call(validator, validator)(target, property, descriptor);
var converters = {};
descriptor.writable = false;
descriptor.configurable = false;
descriptor.enumerable = false;
converters[property] = converter;
(0, _vwebCore.setAnnotation)(target, {
converters: converters
});
};
if (arguments[1]) {
var target = discribe;
discribe = {
validator: {
__all: true
},
converter: {}
function Param(discribe) {
discribe = arguments[0];
const setDescriptor = (target, property, descriptor) => {
const { validator, converter } = discribe;
Validator.call(validator, validator)(target, property, descriptor);
let converters = {};
descriptor.writable = false;
descriptor.configurable = false;
descriptor.enumerable = false;
converters[property] = converter;
setAnnotation(target, { converters });
};
setDescriptor(target, arguments[1], arguments[2]);
} else {
return setDescriptor;
}
if (arguments[1]) {
let target = discribe;
discribe = { validator: { __all: true }, converter: {} };
setDescriptor(target, arguments[1], arguments[2]);
}
else {
return setDescriptor;
}
}
RequestParam.keys = ["validator", "converter"];
function ResponseBody() {
var response = arguments[0];
var set = function set(target, property, descriptor) {
var rests = {};
rests[property] = response;
var annotation = {
rests: rests
exports.Param = Param;
Param.keys = ["validator", "converter"];
function Response() {
let response = arguments[0];
const set = (target, property, descriptor) => {
let rests = {};
rests[property] = response;
let annotation = { rests };
setAnnotation(target, annotation);
};
(0, _vwebCore.setAnnotation)(target, annotation);
};
if (response && arguments[1]) {
var target = response;
response = {
json: true
};
set(target, arguments[1], arguments[2]);
} else {
response = response || {
json: true
};
return set;
}
if (response && arguments[1]) {
let target = response;
response = { json: true };
set(target, arguments[1], arguments[2]);
}
else {
response = response || { json: true };
return set;
}
}
ResponseBody.keys = ["rests"];
module.exports = {
Controller: Controller,
RequestMapping: RequestMapping,
Interceptor: Interceptor,
GetMapping: GetMapping,
PostMapping: PostMapping,
PutMapping: PutMapping,
DeleteMapping: DeleteMapping,
AppScope: AppScope,
Validator: Validator,
RequestParam: RequestParam,
Filter: Filter,
ResponseBody: ResponseBody
};
exports.Response = Response;
Response.keys = ["rests"];
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _anno = require("../anno");
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
var FilterAdapter = /*#__PURE__*/function () {
function FilterAdapter() {
(0, _classCallCheck2["default"])(this, FilterAdapter);
}
(0, _createClass2["default"])(FilterAdapter, [{
key: "ordered",
value: function ordered() {
return -1;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FilterRegulator = exports.FilterAdapter = void 0;
const anno_1 = require("../anno");
class FilterAdapter {
ordered() {
return -1;
}
/**
* 进入controller之前
* @param parameter 请求入参
* @param target 处理请求的controller
* @param handle 响应请求的method
* @param request 请求对象
* @param response 响应对象
* @param session
* @return boolean | undefined 返回false则表示不往下执行
*/
}, {
key: "prepare",
value: function prepare(parameter, _ref) {
var request = _ref.request,
response = _ref.response,
session = _ref.session,
handle = _ref.handle,
target = _ref.target;
return true;
prepare(parameter, { request, response, session, handle, target }) {
return true;
}
/**
* 完成controller之后
* @param parameter 请求入参
* @param result 方法响应结果
* @param target 处理请求的controller
* @param handle 响应请求的method
* @param request 请求对象
* @param response 响应对象
* @param session
*/
}, {
key: "complete",
value: function complete(parameter, result, _ref2) {
var request = _ref2.request,
response = _ref2.response,
session = _ref2.session,
handle = _ref2.handle,
target = _ref2.target;
complete(parameter, result, { request, response, session, handle, target }) {
}
/**
* 请求出现错误的时候
* @param error 错误对象
* @param target 处理请求的controller
* @param handle 响应请求的method
* @param request 请求对象
* @param response 响应对象
* @param session
*/
}, {
key: "throw",
value: function _throw(error, _ref3) {
var request = _ref3.request,
response = _ref3.response,
session = _ref3.session,
handle = _ref3.handle,
target = _ref3.target;
throw(error, { request, response, session, handle, target }) {
}
}]);
return FilterAdapter;
}();
var FilterChain = /*#__PURE__*/function () {
function FilterChain(context, filters) {
(0, _classCallCheck2["default"])(this, FilterChain);
this.context = context;
this.logger = context.log4j.getLogger(FilterChain);
this.filters = filters.sort(function (f1, f2) {
return f1.ordered() - f2.ordered();
});
}
(0, _createClass2["default"])(FilterChain, [{
key: "prepare",
value: function () {
var _prepare = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(parameter, options) {
var _iterator, _step, filter, rs;
return _regenerator["default"].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.prev = 0;
_iterator = _createForOfIteratorHelper(this.filters);
_context.prev = 2;
_iterator.s();
case 4:
if ((_step = _iterator.n()).done) {
_context.next = 14;
break;
}
exports.FilterAdapter = FilterAdapter;
class FilterChain {
constructor(context, filters) {
this.context = context;
this.logger = context.log4j.getLogger(FilterChain);
this.filters = filters.sort((f1, f2) => f1.ordered() - f2.ordered());
}
prepare(parameter, options) {
return __awaiter(this, void 0, void 0, function* () {
try {
for (let filter of this.filters) {
this.logger.debug(`Do filter ${filter.annotation.name} prepare `);
let rs = yield filter.prepare(parameter, options);
if (rs === false) {
return false;
}
}
filter = _step.value;
this.logger.debug("Do filter ".concat(filter.annotation.name, " prepare "));
_context.next = 9;
return filter.prepare(parameter, options);
case 9:
rs = _context.sent;
if (!(rs === false)) {
_context.next = 12;
break;
}
return _context.abrupt("return", false);
case 12:
_context.next = 4;
break;
case 14:
_context.next = 19;
break;
case 16:
_context.prev = 16;
_context.t0 = _context["catch"](2);
_iterator.e(_context.t0);
case 19:
_context.prev = 19;
_iterator.f();
return _context.finish(19);
case 22:
return _context.abrupt("return", true);
case 25:
_context.prev = 25;
_context.t1 = _context["catch"](0);
this.logger.error(_context.t1);
case 28:
case "end":
return _context.stop();
return true;
}
}
}, _callee, this, [[0, 25], [2, 16, 19, 22]]);
}));
function prepare(_x, _x2) {
return _prepare.apply(this, arguments);
}
return prepare;
}()
}, {
key: "complete",
value: function complete(parameter, result, options) {
try {
for (var i = this.filters.length - 1; i >= 0; i--) {
var filter = this.filters[i];
this.logger.debug("Do filter ".concat(filter.annotation.name, " complete "));
filter.complete(parameter, result, options);
}
} catch (e) {
this.logger.error(e);
}
catch (e) {
this.logger.error(e);
}
});
}
}, {
key: "throw",
value: function _throw(error, options) {
try {
for (var i = this.filters.length - 1; i >= 0; i--) {
this.filters[i]["throw"](error, options);
complete(parameter, result, options) {
try {
for (let i = this.filters.length - 1; i >= 0; i--) {
let filter = this.filters[i];
this.logger.debug(`Do filter ${filter.annotation.name} complete `);
filter.complete(parameter, result, options);
}
}
} catch (e) {
this.logger.error(e);
}
catch (e) {
this.logger.error(e);
}
}
}]);
return FilterChain;
}(); // 管理过滤器
var FilterRegulator = /*#__PURE__*/function () {
function FilterRegulator(context) {
(0, _classCallCheck2["default"])(this, FilterRegulator);
this.context = context;
this.filterMap = new Map();
this.logger = context.log4j.getLogger('FilterRegulator');
}
(0, _createClass2["default"])(FilterRegulator, [{
key: "startup",
value: function startup() {
var _this = this;
var context = this.context,
logger = this.logger,
filters = this.filters;
context.getComponent(_anno.Filter, true).forEach(function (filter) {
if (filter instanceof FilterAdapter) {
var regex = filter.annotation.path;
if (!regex) return;
if (regex instanceof RegExp) {
_this.filterMap.set(regex, filter);
return;
}
if (!regex.startsWith('/')) {
regex = '/' + regex;
} // 支持的格式为 /abs/* /abc/** /abc/*/** 等等
regex = regex.replace('**', '.@').replace('*', '[^/]*').replace('@', '*');
_this.filterMap.set(new RegExp(regex, 'g'), filter);
} else {
logger.warn('Filter must extends from FilterAdapter');
throw(error, options) {
try {
for (let i = this.filters.length - 1; i >= 0; i--) {
this.filters[i].throw(error, options);
}
}
});
catch (e) {
this.logger.error(e);
}
}
}, {
key: "getFilterChain",
value: function getFilterChain(req) {
var path = req.path;
var context = this.context,
filterMap = this.filterMap;
var filters = [];
var _iterator2 = _createForOfIteratorHelper(filterMap.keys()),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var regex = _step2.value;
if (regex.test(path)) {
filters.push(filterMap.get(regex));
}
}
class FilterRegulator {
constructor(context) {
this.context = context;
this.filterMap = new Map();
this.logger = context.log4j.getLogger('FilterRegulator');
}
startup() {
let { context, logger, filterMap } = this;
context.getComponent(anno_1.Filter, true).forEach((filter) => {
if (filter instanceof FilterAdapter) {
let regex = filter.annotation.path;
if (!regex)
return;
if (regex instanceof RegExp) {
filterMap.set(regex, filter);
return;
}
if (!regex.startsWith('/')) {
regex = '/' + regex;
}
regex = regex.replace('**', '.@').replace('*', '[^/]*').replace('@', '*');
filterMap.set(new RegExp(regex, 'g'), filter);
}
else {
logger.warn('Filter must extends from FilterAdapter');
}
});
}
getFilterChain(req) {
let path = req.path;
let { context, filterMap } = this;
let filters = [];
for (let regex of filterMap.keys()) {
if (regex.test(path)) {
filters.push(filterMap.get(regex));
}
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
return new FilterChain(context, filters);
return new FilterChain(context, filters);
}
}]);
return FilterRegulator;
}();
module.exports = {
FilterRegulator: FilterRegulator,
FilterAdapter: FilterAdapter
};
}
exports.FilterRegulator = FilterRegulator;
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _anno = require("../anno");
var _model = require("../model");
var _error = require("../error");
var _MessageConverter = require("./MessageConverter");
var _Parameter = _interopRequireDefault(require("./Parameter"));
var _Response = _interopRequireDefault(require("./Response"));
var _vwebCore = require("vweb-core");
var _filter = require("./filter");
var _wrapper = _interopRequireDefault(require("../session/wrapper"));
var _require = require('../model'),
Fail = _require.Fail;
var handlerAdapter = function handlerAdapter(component, method, req, res, next) {
var context = this.context,
parameterConverters = this.parameterConverters,
messageConverters = this.messageConverters,
parameterValidators = this.parameterValidators;
var logger = this.logger,
filterRegulator = this.filterRegulator;
var controller = component.constructor.name;
var _component$annotation = component.annotation,
name = _component$annotation.name,
_component$annotation2 = _component$annotation.rests,
rests = _component$annotation2 === void 0 ? {} : _component$annotation2;
var timeBegin = Date.now(); // 获取注解上的converters
var parameter = _Parameter["default"].create(messageConverters, parameterConverters[name] ? parameterConverters[name][method] : void 0, component[method], req, res, next);
var filterChain = filterRegulator.getFilterChain(req);
var chainOptions = {
target: controller,
handle: method,
request: req,
response: res,
session: new _wrapper["default"](req.session)
};
filterChain.prepare(parameter, chainOptions).then(function (prepare) {
// 如果拦截器返回false 直接返回
if (prepare === false) {
logger.debug('Filter interrupt request');
return;
}
var response = new _Response["default"](req, res, component, logger);
var proxy = new Proxy(component, {
get: function get(target, prop, receiver) {
var returnValue = target[prop];
if (returnValue) return returnValue;
if (typeof response[prop] === 'function') {
returnValue = function returnValue() {
return response[prop].apply(response, Array.prototype.slice.call(arguments));
};
} else {
returnValue = target[prop] = context.getComponent(prop);
Object.defineProperty(exports, "__esModule", { value: true });
const anno_1 = require("../anno");
const model_1 = require("../model");
const error_1 = require("../error");
const MessageConverter_1 = require("./MessageConverter");
const Parameter_1 = require("./Parameter");
const Response_1 = require("./Response");
const filter_1 = require("./filter");
const wrapper_1 = require("../session/wrapper");
const model_2 = require("../model");
const index_1 = require("../interceptor/index");
let createError = require('http-errors');
let { util, LogicError } = require('vweb-core');
let http = require('http');
const handlerAdapter = function (component, method, req, res, next) {
const { context, parameterConverters, messageConverters, parameterValidators } = this;
const { logger, filterRegulator } = this;
const controller = component.constructor.name;
const { name, rests = {} } = component.annotation;
const timeBegin = Date.now();
let parameter = Parameter_1.default.create(messageConverters, parameterConverters[name] ? parameterConverters[name][method] : void 0, component[method], req, res, next);
let filterChain = filterRegulator.getFilterChain(req);
let chainOptions = {
target: controller,
handle: method,
request: req,
response: res,
session: new wrapper_1.default(req.session)
};
filterChain.prepare(parameter, chainOptions).then(prepare => {
if (prepare === false) {
logger.debug('Filter interrupt request');
return;
}
return returnValue;
}
});
var value;
try {
parameterValidators[name] && parameter.validate(proxy, parameterValidators[name][method]);
value = proxy[method].apply(proxy, parameter.getArgs());
if (value) {
var end = function end(result) {
var rest = rests[method];
if (rest) return proxy[rest.json ? 'json' : 'send'](result);
if (result instanceof _model.View) {
proxy[result.signature()].apply(proxy, (0, _toConsumableArray2["default"])(result.getArg()));
} else if (result instanceof _model.RestModel) {
proxy.json(result);
} else if (typeof result === 'string') {
var _method = "view";
var index = result.indexOf(":");
index = index === -1 ? 0 : index + 1;
var path = result;
if (result.startsWith("redirect:")) {
_method = "redirect";
path = result.substring(index);
} else if (result.startsWith("forward:")) {
_method = "forward";
path = result.substring(index);
} else if (/^http[s]?:/.test(result)) {
_method = "redirect";
let response = new Response_1.default(req, res, component, logger);
let proxy = new Proxy(component, {
get: (target, prop, receiver) => {
let returnValue = target[prop];
if (returnValue)
return returnValue;
if (typeof response[prop] === 'function') {
returnValue = function () {
return response[prop].apply(response, Array.prototype.slice.call(arguments));
};
}
else {
returnValue = target[prop] = context.getComponent(prop);
}
return returnValue;
}
proxy[_method](path);
} else {
proxy.success(result);
}
filterChain.complete(parameter, result, chainOptions);
};
if (value instanceof Promise) {
value.then(end)["catch"](function (err) {
return (0, _error.requestError)(res, err, logger);
});
} else {
end(value);
});
let value;
try {
parameterValidators[name] && parameter.validate(proxy, parameterValidators[name][method]);
value = proxy[method].apply(proxy, parameter.getArgs());
if (value) {
const end = result => {
let rest = rests[method];
if (rest)
return proxy[rest.json ? 'json' : 'send'](result);
if (result instanceof model_1.View) {
proxy[result.signature()](...result.getArg());
}
else if (result instanceof model_1.RestModel) {
proxy.json(result);
}
else if (typeof result === 'string') {
let method = "view";
let index = result.indexOf(":");
index = index === -1 ? 0 : index + 1;
let path = result;
if (result.startsWith("redirect:")) {
method = "redirect";
path = result.substring(index);
}
else if (result.startsWith("forward:")) {
method = "forward";
path = result.substring(index);
}
else if (/^http[s]?:/.test(result)) {
method = "redirect";
}
proxy[method](path);
}
else {
proxy.success(result);
}
filterChain.complete(parameter, result, chainOptions);
};
if (value instanceof Promise) {
value.then(end).catch(err => (0, error_1.requestError)(res, err, logger));
}
else {
end(value);
}
}
else {
if (!parameter.contains("res") && !parameter.contains("response")) {
proxy.view();
}
}
}
} else {
// 如果未传递response且无返回值 使用请求作为返回值
if (!parameter.contains("res") && !parameter.contains("response")) {
proxy.view();
catch (err) {
filterChain.throw(err, req, res);
(0, error_1.requestError)(res, err, logger);
logger.info(`from ${req.ip} ${req.method} ${req.url} cost ${Date.now() - timeBegin}ms`);
}
}
} catch (err) {
filterChain["throw"](err, req, res);
(0, _error.requestError)(res, err, logger);
logger.info("from ".concat(req.ip, " ").concat(req.method, " ").concat(req.url, " cost ").concat(Date.now() - timeBegin, "ms"));
}).catch(err => {
filterChain.throw(err, chainOptions);
});
};
class ControllerAdapter {
constructor(context, express, config) {
let { log4j } = context;
this.logger = log4j.getLogger('Controller');
this.mappings = {};
this.express = express;
this.config = config;
this.context = context;
this.controllers = [];
this.filterRegulator = new filter_1.FilterRegulator(context);
this.messageConverters = [new MessageConverter_1.NumberMessageConverter()];
this.parameterConverters = {};
this.parameterValidators = {};
this.handlerMappings = new Map();
}
})["catch"](function (err) {
filterChain["throw"](err, chainOptions);
});
};
/**
* http 控制器
*/
var ControllerAdapter = /*#__PURE__*/function () {
function ControllerAdapter(context, express, config) {
(0, _classCallCheck2["default"])(this, ControllerAdapter);
var log4j = context.log4j;
this.logger = log4j.getLogger('Controller');
this.mappings = {};
this.express = express;
this.config = config;
this.context = context;
this.controllers = [];
this.filterRegulator = new _filter.FilterRegulator(context);
this.messageConverters = [new _MessageConverter.NumberMessageConverter()];
this.parameterConverters = {};
this.parameterValidators = {};
this.handlerMappings = new Map();
}
(0, _createClass2["default"])(ControllerAdapter, [{
key: "init",
value: function init() {
var _this = this,
_this$messageConverte;
var express = this.express,
context = this.context,
controllers = this.controllers,
parameterConverters = this.parameterConverters,
parameterValidators = this.parameterValidators,
handlerMappings = this.handlerMappings,
logger = this.logger; // 初始化拦截器 拦截器必须初始化在controller之前 否则不生效
require('../interceptor')(context, express); // 过滤器初始化
this.filterRegulator.startup();
var log4j = context.log4j;
var mappingPool = {};
controllers.forEach(function (controller) {
var _controller$annotatio = controller.annotation,
mapping = _controller$annotatio.mapping,
_controller$annotatio2 = _controller$annotatio.mappings,
mappings = _controller$annotatio2 === void 0 ? {} : _controller$annotatio2,
name = _controller$annotatio.name,
_controller$annotatio3 = _controller$annotatio.validators,
validators = _controller$annotatio3 === void 0 ? {} : _controller$annotatio3,
_controller$annotatio4 = _controller$annotatio.converters,
converters = _controller$annotatio4 === void 0 ? {} : _controller$annotatio4;
if (!mappings) {
logger.warn("Controller ".concat(name, " does not define RequestMapping"));
return;
}
parameterConverters[name] = converters;
parameterValidators[name] = validators;
var root = mapping ? mapping.value : '';
if (!_this.mappings[name]) _this.mappings[name] = [];
var logger = log4j.getLogger(name);
Object.keys(mappings).forEach(function (methodName) {
mappings[methodName].forEach(function (_ref) {
var value = _ref.value,
method = _ref.method;
var path = "/".concat(root).concat(value ? '/' + value : '');
while (path.includes('//')) {
path = path.replace(/\/\//g, '/');
init() {
const { express, context, controllers, parameterConverters, parameterValidators, handlerMappings, logger } = this;
(0, index_1.default)(context, express);
this.filterRegulator.startup();
let { log4j } = context;
let mappingPool = {};
controllers.forEach(controller => {
const { mapping, mappings = {}, name, validators = {}, converters = {} } = controller.annotation;
if (!mappings) {
this.logger.warn(`Controller ${name} does not define RequestMapping`);
return;
}
_this.mappings[name].push({
path: path,
method: method
parameterConverters[name] = converters;
parameterValidators[name] = validators;
const root = mapping ? mapping.value : '';
if (!this.mappings[name])
this.mappings[name] = [];
const logger = log4j.getLogger(name);
Object.keys(mappings).forEach(methodName => {
mappings[methodName].forEach(({ value, method }) => {
let path = `/${root}${value ? '/' + value : ''}`;
while (path.includes('//'))
path = path.replace(/\/\//g, '/');
this.mappings[name].push({ path, method });
let key = `${method}-${path}`;
if (!mappingPool[key]) {
mappingPool[key] = name;
}
else {
throw new Error(`Request ${key} duplicate definition in ${name},${mappingPool[key]}`);
}
let fnString = controller[methodName].toString();
if (fnString.includes(`return _${methodName}.apply(this, arguments);`)) {
throw new Error(`Handler method ${controller.constructor.name}.${methodName} can't defined async method`);
}
let handler = (req, res, next) => handlerAdapter.call(this, controller, methodName, req, res, next);
handlerMappings.set(method + '|' + path, handler);
express[method](path, handler);
});
});
var key = "".concat(method, "-").concat(path);
if (!mappingPool[key]) {
mappingPool[key] = name;
} else {
throw new Error("Request ".concat(key, " duplicate definition in ").concat(name, ",").concat(mappingPool[key]));
} // 检查是否为async函数
// 如果为async函数 入参会被改变 无法使用参数接收入参
var fnString = controller[methodName].toString();
if (fnString.includes("return _".concat(methodName, ".apply(this, arguments);"))) {
throw new Error("Handler method ".concat(controller.constructor.name, ".").concat(methodName, " can't defined async method"));
} // 添加路由监听
var handler = function handler(req, res, next) {
return handlerAdapter.call(_this, controller, methodName, req, res, next);
};
handlerMappings.set(method + '|' + path, handler);
express[method](path, handler);
});
logger.info('Request ' + this.mappings[name].map(({ path, method }) => `[${method}=${path}]`).join(' '));
});
logger.info('Request ' + _this.mappings[name].map(function (_ref2) {
var path = _ref2.path,
method = _ref2.method;
return "[".concat(method, "=").concat(path, "]");
}).join(' '));
}); // 初始化appScope
context.getComponent(_anno.AppScope, true).forEach(function (scope) {
return express.locals['$' + scope.annotation.name] = scope;
}); // 初始化messageConverts
(_this$messageConverte = this.messageConverters).push.apply(_this$messageConverte, (0, _toConsumableArray2["default"])(context.getComponent(_MessageConverter.HttpMessageConverter, true)));
context.getComponent(anno_1.Scope, true).forEach(scope => express.locals['$' + scope.annotation.name] = scope);
this.messageConverters.push(...context.getComponent(MessageConverter_1.HttpMessageConverter, true));
}
}, {
key: "startup",
value: function startup() {
var _this$controllers;
var logger = this.logger,
context = this.context,
express = this.express,
_this$config$port = this.config.port,
port = _this$config$port === void 0 ? process.env.PORT || 3000 : _this$config$port;
(_this$controllers = this.controllers).push.apply(_this$controllers, (0, _toConsumableArray2["default"])(context.getComponent(_anno.Controller, true)));
var createError = require('http-errors');
this.init(); // 必须声明在use之后 否则未做解析 导致post body无法解析
express.use(function (req, res, next) {
next(createError(404));
}).use(function (err, req, res, next) {
res.locals.message = err.message;
var _process$env$active = process.env.active,
active = _process$env$active === void 0 ? 'development' : _process$env$active;
res.locals.error = active === 'development' ? err : {};
res.status(err.status || 500);
err.message = "".concat(err.message, "\u3010").concat(req.originalUrl, "\u3011");
if (!req.originalUrl.endsWith(".ico") && err.status !== 404) {
logger.error(err);
}
logger.debug(err);
if (!req.xhr) {
res.render('error', {
err: err
});
} else {
res.json(new Fail(err.message, err.status || 500));
}
});
var http = require('http');
var server = http.createServer(express);
server.listen(port);
server.on('error', function (error) {
if (error.syscall !== 'listen') {
throw error;
}
var serverPort = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port;
switch (error.code) {
case 'EACCES':
logger.error(serverPort + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
logger.error(serverPort + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
});
server.on('listening', function () {
var addr = server.address();
var bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port;
var _util$ipAddress = _vwebCore.util.ipAddress(),
ip = _util$ipAddress.ip;
logger.info("Server start on ".concat(bind, " address is http://").concat(ip, ":").concat(port));
});
context.register({
name: 'vweb-server'
}, server);
startup() {
const { logger, context, express, config: { port = process.env.PORT || 3000 } } = this;
this.controllers.push(...context.getComponent(anno_1.Controller, true));
this.init();
express.use(function (req, res, next) {
next(createError(404));
})
.use(function (err, req, res, next) {
res.locals.message = err.message;
let { active = 'development' } = process.env;
res.locals.error = active === 'development' ? err : {};
res.status(err.status || 500);
err.message = `${err.message}【${req.originalUrl}】`;
if (!req.originalUrl.endsWith(".ico") && err.status !== 404) {
logger.error(err);
}
logger.debug(err);
if (!req.xhr) {
res.render('error', { err });
}
else {
res.json(new model_2.Fail(err.message, err.status || 500));
}
});
const server = http.createServer(express);
server.listen(port);
server.on('error', (error) => {
if (error.syscall !== 'listen') {
throw error;
}
let serverPort = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
switch (error.code) {
case 'EACCES':
logger.error(serverPort + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
logger.error(serverPort + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
});
server.on('listening', () => {
let addr = server.address();
let bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
let { ip } = util.ipAddress();
logger.info(`Server start on ${bind} address is http://${ip}:${port}`);
});
context.register({ name: 'vweb-server' }, server);
}
}]);
return ControllerAdapter;
}();
var _default = ControllerAdapter;
exports["default"] = _default;
}
exports.default = ControllerAdapter;
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var HttpMessageConverter = /*#__PURE__*/function () {
function HttpMessageConverter(pattern) {
(0, _classCallCheck2["default"])(this, HttpMessageConverter);
this.pattern = pattern;
}
(0, _createClass2["default"])(HttpMessageConverter, [{
key: "convert",
value: function convert(name, value) {
return value;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConvertWorker = exports.NumberMessageConverter = exports.HttpMessageConverter = void 0;
class HttpMessageConverter {
constructor(pattern) {
this.pattern = pattern;
}
}, {
key: "matches",
value: function matches(name, value) {
return this.pattern.test(value);
convert(name, value) {
return value;
}
}]);
return HttpMessageConverter;
}();
var NumberMessageConverter = /*#__PURE__*/function (_HttpMessageConverter) {
(0, _inherits2["default"])(NumberMessageConverter, _HttpMessageConverter);
var _super = _createSuper(NumberMessageConverter);
function NumberMessageConverter() {
(0, _classCallCheck2["default"])(this, NumberMessageConverter);
return _super.call(this, void 0);
}
(0, _createClass2["default"])(NumberMessageConverter, [{
key: "convert",
value: function convert(name, value) {
var val = value.indexOf('.') !== -1 ? parseFloat(value) : parseInt(value);
if (val !== Infinity) return val;
return value;
matches(name, value) {
return this.pattern.test(value);
}
}, {
key: "matches",
value: function matches(name, value) {
return /^[+-]?\d+(\.\d+)?$/.test(value) && /(\w*Id)|count|value|cost/.test(name);
}
exports.HttpMessageConverter = HttpMessageConverter;
class NumberMessageConverter extends HttpMessageConverter {
constructor() {
super(void 0);
}
}]);
return NumberMessageConverter;
}(HttpMessageConverter);
var ConvertWorker = /*#__PURE__*/function () {
function ConvertWorker() {
(0, _classCallCheck2["default"])(this, ConvertWorker);
}
(0, _createClass2["default"])(ConvertWorker, null, [{
key: "string2bigint",
value: function string2bigint(value) {
return BigInt(value);
convert(name, value) {
let val = value.indexOf('.') !== -1 ? parseFloat(value) : parseInt(value);
if (val !== Infinity)
return val;
return value;
}
}, {
key: "string2int",
value: function string2int(value) {
return parseInt(value, 10);
matches(name, value) {
return /^[+-]?\d+(\.\d+)?$/.test(value) && /(\w*Id)|count|value|cost/.test(name);
}
}, {
key: "string2float",
value: function string2float(value) {
return parseFloat(value);
}
exports.NumberMessageConverter = NumberMessageConverter;
class ConvertWorker {
static string2bigint(value) {
return BigInt(value);
}
}, {
key: "convert",
value: function convert(obj, descr) {
var _loop = function _loop(fields) {
if (!descr.hasOwnProperty(fields)) return "continue";
var converter = descr[fields];
fields.split(',').forEach(function (field) {
field = field.trim();
var value = obj[field];
if (typeof converter === "string") {
obj[field] = ConvertWorker[converter](value);
} else if (typeof converter === 'function') {
obj[field] = converter.call(ConvertWorker, value);
} else {
throw new Error("Unsupport converter ".concat(converter));
}
});
};
for (var fields in descr) {
var _ret = _loop(fields);
if (_ret === "continue") continue;
}
return obj;
static string2int(value) {
return parseInt(value, 10);
}
}]);
return ConvertWorker;
}();
module.exports = {
HttpMessageConverter: HttpMessageConverter,
NumberMessageConverter: NumberMessageConverter,
ConvertWorker: ConvertWorker
};
static string2float(value) {
return parseFloat(value);
}
static convert(obj, descr) {
for (let fields in descr) {
if (!descr.hasOwnProperty(fields))
continue;
let converter = descr[fields];
fields.split(',').forEach(field => {
field = field.trim();
let value = obj[field];
if (typeof converter === "string") {
obj[field] = ConvertWorker[converter](value);
}
else if (typeof converter === 'function') {
obj[field] = converter.call(ConvertWorker, value);
}
else {
throw new Error(`Unsupport converter ${converter}`);
}
});
}
return obj;
}
}
exports.ConvertWorker = ConvertWorker;
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _MessageConverter = require("./MessageConverter");
var _ParameterValidError = _interopRequireDefault(require("../error/ParameterValidError"));
var _wrapper = _interopRequireDefault(require("../session/wrapper"));
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var getParamNames = function getParamNames(method) {
var paramString = method.valueOf().toString();
var params = paramString.substring(paramString.indexOf("(") + 1, paramString.indexOf(")"));
return params.split(",").map(function (item) {
var argName = item.trim();
if (/_ref[0-9]*/.test(argName)) {
return '_body';
}
return argName;
});
Object.defineProperty(exports, "__esModule", { value: true });
exports.MultiFile = void 0;
const MessageConverter_1 = require("./MessageConverter");
const error_1 = require("../error");
const wrapper_1 = require("../session/wrapper");
const getParamNames = method => {
let paramString = method.valueOf().toString();
let params = paramString.substring(paramString.indexOf("(") + 1, paramString.indexOf(")"));
return params.split(",").map(item => {
let argName = item.trim();
if (/_ref[0-9]*/.test(argName)) {
return '_body';
}
return argName;
});
};
var paramWrap = function paramWrap(req) {
var requestParams = {};
{
var ip = req.ip;
if (ip) {
var arr = ip.match(/[0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}/g);
if (Array.isArray(arr)) {
ip = arr[0];
}
const paramWrap = req => {
let requestParams = {};
{
let ip = req.ip;
if (ip) {
let arr = ip.match(/[0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}/g);
if (Array.isArray(arr)) {
ip = arr[0];
}
}
req.remote = { ip, device: req.headers['user-agent'] };
}
req.remote = {
ip: ip,
device: req.headers['user-agent']
let params = Object.assign(Object.assign(Object.assign({}, req.params), req.query), req.body);
params.toJSON = () => {
if (Array.isArray(req.body)) {
return req.body;
}
return Object.assign(Object.assign(Object.assign({}, req.params), req.query), req.body);
};
}
var params = _objectSpread(_objectSpread(_objectSpread({}, req.params), req.query), req.body);
params.toJSON = function () {
if (Array.isArray(req.body)) {
return req.body;
}
return _objectSpread(_objectSpread(_objectSpread({}, req.params), req.query), req.body);
};
Reflect.ownKeys(params).forEach(function (key) {
key = key.replace(/\[\w+\]/g, function (key) {
return "." + key.substring(1, key.length - 1);
Reflect.ownKeys(params).forEach((key) => {
key = key.replace(/\[\w+\]/g, key => "." + key.substring(1, key.length - 1));
let rp = params[key];
let tmp = requestParams;
key.split('.').forEach((e, i, arr) => {
if (arr.length - 1 === i) {
if (tmp[e] && tmp instanceof Array) {
tmp[e].push(rp);
}
else {
tmp[e] = rp;
}
}
else {
if (!tmp[e])
tmp[e] = {};
tmp = tmp[e];
}
});
});
var rp = params[key];
var tmp = requestParams;
key.split('.').forEach(function (e, i, arr) {
if (arr.length - 1 === i) {
if (tmp[e] && tmp instanceof Array) {
tmp[e].push(rp);
} else {
tmp[e] = rp;
}
} else {
if (!tmp[e]) tmp[e] = {};
tmp = tmp[e];
}
});
});
return requestParams;
return requestParams;
};
var Parameter = /*#__PURE__*/function () {
/**
*
* @param messageConverters 全局定义的解析器
* @param paramConverter 在RequestParam 中定义的解析器
*/
function Parameter() {
var messageConverters = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var paramConverter = arguments.length > 1 ? arguments[1] : undefined;
(0, _classCallCheck2["default"])(this, Parameter);
this.messageConverters = messageConverters;
this.paramConverter = paramConverter;
this.params = [];
this.values = [];
this.body = {};
this.parameters = void 0;
this.method = void 0;
}
(0, _createClass2["default"])(Parameter, [{
key: "get",
value: function get(name) {
return this.values[this.params.indexOf(name)];
class Parameter {
constructor(messageConverters = [], paramConverter) {
this.messageConverters = messageConverters;
this.paramConverter = paramConverter;
this.params = [];
this.values = [];
this.body = {};
this.parameters = void 0;
this.method = void 0;
}
}, {
key: "contains",
value: function contains(names) {
if (Array.isArray(names)) {
var _iterator = _createForOfIteratorHelper(names),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var name = _step.value;
if (this.params.indexOf(name) !== -1) {
return true;
get(name) {
return this.values[this.params.indexOf(name)];
}
contains(names) {
if (Array.isArray(names)) {
for (let name of names) {
if (this.params.indexOf(name) !== -1) {
return true;
}
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
return false;
}
return false;
} else {
return this.params.indexOf(names) !== -1;
}
else {
return this.params.indexOf(names) !== -1;
}
}
}, {
key: "getBody",
value: function getBody() {
return this.body;
getBody() {
return this.body;
}
}, {
key: "setMethod",
value: function setMethod(method, parameters) {
var _this = this;
this.method = method;
this.parameters = parameters;
getParamNames(method).forEach(function (param) {
_this.put(param, /^_file_/.test(param) ? new MultiFile(parameters['_files'][param.substring(6)]) : parameters[param]);
});
setMethod(method, parameters) {
this.method = method;
this.parameters = parameters;
getParamNames(method).forEach(param => {
this.put(param, /^_file_/.test(param) ? new MultiFile(parameters['_files'][param.substring(6)]) : parameters[param]);
});
}
}, {
key: "set",
value: function set(name, value) {
value = this.convert(name, value);
this.values[this.params.indexOf(name)] = value;
this.body[name] = value;
set(name, value) {
value = this.convert(name, value);
this.values[this.params.indexOf(name)] = value;
this.body[name] = value;
}
}, {
key: "convert",
value: function convert(name, value) {
var _iterator2 = _createForOfIteratorHelper(this.messageConverters),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var messageConverter = _step2.value;
if (messageConverter.matches(name, value)) {
value = messageConverter.convert(name, value);
}
convert(name, value) {
for (let messageConverter of this.messageConverters) {
if (messageConverter.matches(name, value)) {
value = messageConverter.convert(name, value);
}
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
if (name in this.paramConverter) {
var converter = this.paramConverter[name];
if (typeof converter === "function") {
value = converter.call(_MessageConverter.ConvertWorker, value);
} else if (_MessageConverter.ConvertWorker[converter]) {
value = _MessageConverter.ConvertWorker[converter](value);
} else {
value = converter;
if (name in this.paramConverter) {
let converter = this.paramConverter[name];
if (typeof converter === "function") {
value = converter.call(MessageConverter_1.ConvertWorker, value);
}
else if (MessageConverter_1.ConvertWorker[converter]) {
value = MessageConverter_1.ConvertWorker[converter](value);
}
else {
value = converter;
}
}
}
return value;
return value;
}
}, {
key: "put",
value: function put(name, value) {
this.params.push(name);
value = this.convert(name, value);
this.values.push(value);
this.body[name] = value;
put(name, value) {
this.params.push(name);
value = this.convert(name, value);
this.values.push(value);
this.body[name] = value;
}
}, {
key: "getArgs",
value: function getArgs() {
return this.values;
getArgs() {
return this.values;
}
}, {
key: "forEach",
value: function forEach(fn) {
var _this2 = this;
this.params.forEach(function (param, index) {
return fn(param, _this2.values[index]);
});
forEach(fn) {
this.params.forEach((param, index) => fn(param, this.values[index]));
}
}, {
key: "validate",
value: function validate(target, validators) {
var _this3 = this;
if (!validators) return;
if (typeof validators === "function") {
if (validators.call(this, this.parameters) === false) {
throw new _ParameterValidError["default"]("Parameter invalid");
validate(target, validators) {
if (!validators)
return;
if (typeof validators === "function") {
if (validators.call(this, this.parameters) === false) {
throw new error_1.ParameterValidError(`Parameter invalid`);
}
return;
}
return;
}
var errors = [];
Reflect.ownKeys(validators).forEach(function (param) {
try {
var value = _this3.parameters[param] || _this3.get(param);
var validator = validators[param];
if (validator === true) {
if (!value) {
errors.push("Require parameter ".concat(param, ", but not found"));
let errors = [];
Reflect.ownKeys(validators).forEach((param) => {
try {
let value = this.parameters[param] || this.get(param);
let validator = validators[param];
if (validator === true) {
if (!value) {
errors.push(`Require parameter ${param}, but not found`);
}
}
else if (typeof validator === "function") {
let rs = validator.call(this.parameters, value, param);
if (rs === false) {
errors.push(`Parameter ${param} invalid`);
}
}
else if (typeof validator === 'string' || validator instanceof RegExp) {
if (!(validator instanceof RegExp ? validator : new RegExp(validator)).test(value || '')) {
errors.push(`Parameter ${param} not matches`);
}
}
}
} else if (typeof validator === "function") {
var rs = validator.call(_this3.parameters, value, param);
if (rs === false) {
errors.push("Parameter ".concat(param, " invalid"));
catch (e) {
errors.push(e.message);
}
} else if (typeof validator === 'string' || validator instanceof RegExp) {
if (!(validator instanceof RegExp ? validator : new RegExp(validator)).test(value || '')) {
errors.push("Parameter ".concat(param, " not matches"));
}
}
} catch (e) {
errors.push(e.message);
});
if (errors.length) {
throw new error_1.ParameterValidError(errors.join(','));
}
});
if (errors.length) {
throw new _ParameterValidError["default"](errors.join(','));
}
}
}], [{
key: "create",
value: function create(messageConverters) {
var paramConverter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var method = arguments.length > 2 ? arguments[2] : undefined;
var req = arguments.length > 3 ? arguments[3] : undefined;
var res = arguments.length > 4 ? arguments[4] : undefined;
var next = arguments.length > 5 ? arguments[5] : undefined;
var parameters = paramWrap(req);
parameters['_body'] = _objectSpread({}, parameters);
parameters['_headers'] = req.headers;
parameters['req'] = parameters['request'] = req;
parameters['context'] = req.context || {};
parameters['res'] = parameters['response'] = res;
parameters['session'] = req.session && new _wrapper["default"](req.session);
parameters['cookie'] = req.cookie;
parameters['next'] = next;
var files = req.files;
var _files = {};
files && Object.keys(files).forEach(function (key) {
_files[key] = new MultiFile(files[key]);
});
parameters['_files'] = _files;
var parameter = new Parameter(messageConverters, paramConverter);
parameter.setMethod(method, parameters);
return parameter;
static create(messageConverters, paramConverter = {}, method, req, res, next) {
let parameters = paramWrap(req);
parameters['_body'] = Object.assign({}, parameters);
parameters['_headers'] = req.headers;
parameters['req'] = parameters['request'] = req;
parameters['context'] = req.context || {};
parameters['res'] = parameters['response'] = res;
parameters['session'] = req.session && new wrapper_1.default(req.session);
parameters['cookie'] = req.cookie;
parameters['next'] = next;
let files = req.files;
let _files = {};
files && Object.keys(files).forEach(key => {
_files[key] = new MultiFile(files[key]);
});
parameters['_files'] = _files;
let parameter = new Parameter(messageConverters, paramConverter);
parameter.setMethod(method, parameters);
return parameter;
}
}]);
return Parameter;
}();
var fs = require("fs");
var MultiFile = /*#__PURE__*/function () {
function MultiFile(file) {
var _this4 = this;
(0, _classCallCheck2["default"])(this, MultiFile);
Object.keys(file).forEach(function (key) {
return _this4[key] = file[key];
});
}
(0, _createClass2["default"])(MultiFile, [{
key: "readXlsx",
value: function readXlsx() {
if (/xlsx$/i.test(this.name)) {
var xlsx = require("node-xlsx");
return xlsx.parse(this.read());
}
throw new Error('仅支持xlsx文件');
;
}
exports.default = Parameter;
const fs = require("fs");
class MultiFile {
constructor(file) {
Object.keys(file).forEach(key => this[key] = file[key]);
}
}, {
key: "readJson",
value: function readJson() {
if (/json$/i.test(this.name)) {
return JSON.parseObject(this.read());
}
throw new Error('仅支持json文件');
readXlsx() {
if (/xlsx$/i.test(this.name)) {
let xlsx = require("node-xlsx");
return xlsx.parse(this.read());
}
throw new Error('仅支持xlsx文件');
}
}, {
key: "readCsv",
value: function readCsv() {
if (/csv$/i.test(this.name)) {
return this.read().split("\r\n").map(function (row) {
return row.split(',');
});
}
throw new Error('仅支持csv文件');
readJson() {
if (/json$/i.test(this.name)) {
return JSON.parse(this.read());
}
throw new Error('仅支持json文件');
}
}, {
key: "read",
value: function read() {
return fs.readFileSync(this.path);
readCsv() {
if (/csv$/i.test(this.name)) {
return this.read().split("\r\n").map(row => row.split(','));
}
throw new Error('仅支持csv文件');
}
}]);
return MultiFile;
}();
var _default = Parameter;
exports["default"] = _default;
read() {
return fs.readFileSync(this.path);
}
}
exports.MultiFile = MultiFile;
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _model = require("../model");
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var qs = require("querystring");
var pathMatches = function pathMatches(path, matches) {
if (path === matches) return true;
if (/:[0-9a-zA-Z]+/.test(matches)) {
matches = matches.replace(/:[0-9a-zA-Z]+/g, '[0-9a-zA-Z]+');
}
return new RegExp("^".concat(matches, "$")).test(path);
Object.defineProperty(exports, "__esModule", { value: true });
const model_1 = require("../model");
const qs = require("querystring");
const pathMatches = (path, matches) => {
if (path === matches)
return true;
if (/:[0-9a-zA-Z]+/.test(matches)) {
matches = matches.replace(/:[0-9a-zA-Z]+/g, '[0-9a-zA-Z]+');
}
return new RegExp(`^${matches}$`).test(path);
};
var Response = /*#__PURE__*/function () {
function Response(req, res, controller, logger) {
(0, _classCallCheck2["default"])(this, Response);
this.__req = req;
this.__res = res;
this.__controller = controller;
this.__logger = logger;
this.__begin = Date.now();
}
(0, _createClass2["default"])(Response, [{
key: "send",
value: function send(model) {
this.__res.send(model);
this.__finally();
class Response {
constructor(req, res, controller, logger) {
this.req = req;
this.res = res;
this.controller = controller;
this.logger = logger;
this.begin = Date.now();
}
}, {
key: "json",
value: function json(model) {
this.__res.json(model);
this.__finally();
send(model) {
this.res.send(model);
this.finally();
}
}, {
key: "success",
value: function success(model) {
this.__res.json(new _model.Success(model));
this.__finally();
json(model) {
this.res.json(model);
this.finally();
}
}, {
key: "fail",
value: function fail(code, describe) {
this.__res.json(new _model.Fail(code, describe));
this.__finally();
success(model) {
this.res.json(new model_1.Success(model));
this.finally();
}
}, {
key: "view",
value: function view(_view, model) {
if (typeof _view !== 'string') {
model = model || _view;
_view = this.__req.route.path.substring(1);
}
this.__res.render(_view, _objectSpread({
session: this.__req.session && this.__req.session.attributes || {}
}, model));
this.__finally("View ".concat(_view, " "));
fail(code, describe) {
this.res.json(new model_1.Fail(code, describe));
this.finally();
}
}, {
key: "forward",
value: function forward(path) {
var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var __req = this.__req,
__res = this.__res;
if (/^http[s]?:/.test(path)) {
if (__req.method === 'delete' || __req.method === 'get') {
var search = qs.stringify(params);
if (search) {
path += (path.includes('?') ? '&' : '?') + search;
}
view(view, model) {
if (typeof view !== 'string') {
model = model || view;
view = this.req.route.path.substring(1);
}
var axios = require("axios");
axios[__req.method](path, params).then(__res.send)["catch"](__res.send)["finally"](this.__finally);
} else {
// 当前服务器跳转 通过路径获取到handlerMappings
var handlerMappings = this.__controller.handlerMappings;
var forwarded = false;
var _iterator = _createForOfIteratorHelper(handlerMappings.entries()),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var _step$value = (0, _slicedToArray2["default"])(_step.value, 2),
match = _step$value[0],
handler = _step$value[1];
if (pathMatches(__req.method + '|' + path, match)) {
__req.params = _objectSpread(_objectSpread({}, __req.params), params);
handler(__req, __res);
forwarded = true;
break;
this.res.render(view, Object.assign({ session: (this.req.session && this.req.session.attributes) || {} }, model));
this.finally(`View ${view} `);
}
forward(path, params = []) {
const { req, res } = this;
if (/^http[s]?:/.test(path)) {
if (req.method === 'delete' || req.method === 'get') {
let search = qs.stringify(params);
if (search) {
path += (path.includes('?') ? '&' : '?') + search;
}
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
let axios = require("axios");
axios[req.method](path, params).then(res.send).catch(res.send).finally(this.finally);
}
if (!forwarded) if (!forwarded) __res.redirect(302, path);
this.__finally();
}
else {
const { handlerMappings } = this.controller;
let forwarded = false;
for (let [match, handler] of handlerMappings.entries()) {
if (pathMatches(req.method + '|' + path, match)) {
req.params = Object.assign(Object.assign({}, req.params), params);
handler(req, res);
forwarded = true;
break;
}
}
if (!forwarded)
if (!forwarded)
res.redirect(302, path);
this.finally();
}
}
}, {
key: "redirect",
value: function redirect(url, params, status) {
if (params) {
url += url.includes('?') ? '&' : '?';
url += qs.stringify(params);
}
this.__res.redirect(status || 302, url);
this.__finally();
redirect(url, params, status) {
if (params) {
url += url.includes('?') ? '&' : '?';
url += qs.stringify(params);
}
this.res.redirect(status || 302, url);
this.finally();
}
}, {
key: "__finally",
value: function __finally() {
var i = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var __req = this.__req;
var info = "".concat(this.__controller.constructor.name, " from ").concat(__req.ip, " ").concat(__req.method, " ").concat(__req.url, " cost ");
info += "".concat(Date.now() - this.__begin, "ms");
this.__logger.info(i + info);
finally(i = '') {
const { req } = this;
let info = `${this.controller.constructor.name} from ${req.ip} ${req.method} ${req.url} cost `;
info += `${Date.now() - this.begin}ms`;
this.logger.info(i + info);
}
}]);
return Response;
}();
var _default = Response;
exports["default"] = _default;
}
exports.default = Response;
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _vwebCore = require("vweb-core");
var _ParameterValidError = _interopRequireDefault(require("./ParameterValidError"));
var _model = require("../model");
var requestError = function requestError(res, err, logger) {
if (err instanceof _vwebCore.LogicError || err.code) {
logger.debug(err);
res.send(new _model.Fail(err.message, err.code || 'LogicError'));
} else {
logger.error(err);
res.send(new _model.Fail(err.message, err.code || 'ServerError'));
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.ParameterValidError = exports.requestError = void 0;
const model_1 = require("../model");
let { LogicError } = require("vweb-core");
const requestError = (res, err, logger) => {
if ((err instanceof LogicError) || err.code) {
logger.debug(err);
res.send(new model_1.Fail(err.message, err.code || 'LogicError'));
}
else {
logger.error(err);
res.send(new model_1.Fail(err.message, err.code || 'ServerError'));
}
};
module.exports = {
requestError: requestError,
ParameterValidError: _ParameterValidError["default"]
};
exports.requestError = requestError;
class ParameterValidError extends require("vweb-core").LogicError {
constructor(message) {
super();
this.message = message;
}
}
exports.ParameterValidError = ParameterValidError;

@@ -1,39 +0,34 @@

export class FilterAdapter {
ordered();
/**
* 进入controller之前
* @param parameter 请求入参
* @param target 处理请求的controller
* @param handle 响应请求的method
* @param request 请求对象
* @param response 响应对象
* @param session
* @return boolean | undefined 返回false则表示不往下执行
*/
prepare(parameter, {request, response, session, handle, target});
/**
* 完成controller之后
* @param parameter 请求入参
* @param result 方法响应结果
* @param target 处理请求的controller
* @param handle 响应请求的method
* @param request 请求对象
* @param response 响应对象
* @param session
*/
complete(parameter, result, {request, response, session, handle, target});
/**
* 请求出现错误的时候
* @param error 错误对象
* @param target 处理请求的controller
* @param handle 响应请求的method
* @param request 请求对象
* @param response 响应对象
* @param session
*/
throw(error, {request, response, session, handle, target});
}
import ControllerAdapter from "./controller/index";
import { Filter, Controller, Interceptor, Request, Get, Post, Put, Delete, Scope, Validator, Param, Response } from "./anno";
import { Fail, Success, RestModel, View, Redirect, Forward } from "./model";
import { HttpInterceptor } from "./interceptor";
import { FilterAdapter } from "./controller/filter";
declare const annotation: {
Controller: typeof Controller;
RequestMapping: typeof Request;
Interceptor: typeof Interceptor;
GetMapping: any;
PostMapping: any;
PutMapping: any;
DeleteMapping: any;
AppScope: typeof Scope;
Validator: typeof Validator;
RequestParam: typeof Param;
ResponseBody: typeof Response;
};
declare const model: {
Fail: typeof Fail;
Success: typeof Success;
RestModel: typeof RestModel;
View: typeof View;
Redirect: typeof Redirect;
Forward: typeof Forward;
};
declare const SUCCESS: Success;
declare const FAIL: Fail;
export { SUCCESS, FAIL, Request, Response, Get, Post, Put, Delete, Scope, Param, HttpInterceptor, Fail, Success, RestModel, View, Redirect, Forward, FilterAdapter, Filter, Validator, Controller, Interceptor, model, annotation, };
declare const _default: {
name: string;
launch: (config: any) => ControllerAdapter;
};
export default _default;
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _controller = _interopRequireDefault(require("./controller"));
var _anno = require("./anno");
var _model = require("./model");
var _interceptor = require("./interceptor");
var _filter = require("./controller/filter");
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var express = require('express');
var multiparty = require('connect-multiparty');
var path = require('path');
var cookieParser = require('cookie-parser');
var compression = require('compression');
var app = express();
module.exports = {
SUCCESS: new _model.Success(),
FAIL: new _model.Fail(),
/**
* @deprecated 弃用 请使用@Filter FilterAdapter 替代
*/
HttpInterceptor: _interceptor.HttpInterceptor,
Fail: _model.Fail,
Success: _model.Success,
RestModel: _model.RestModel,
View: _model.View,
Redirect: _model.Redirect,
Forward: _model.Forward,
Request: _anno.RequestMapping,
Response: _anno.ResponseBody,
FilterAdapter: _filter.FilterAdapter,
Filter: _anno.Filter,
Get: _anno.GetMapping,
Post: _anno.PostMapping,
Put: _anno.PutMapping,
Delete: _anno.DeleteMapping,
Scope: _anno.AppScope,
Validator: _anno.Validator,
Controller: _anno.Controller,
/**
* @deprecated 弃用 请使用@Filter FilterAdapter 替代
*/
Interceptor: _anno.Interceptor,
Param: _anno.RequestParam,
model: {
Fail: _model.Fail,
Success: _model.Success,
RestModel: _model.RestModel,
View: _model.View,
Redirect: _model.Redirect,
Forward: _model.Forward
},
annotation: {
Controller: _anno.Controller,
RequestMapping: _anno.RequestMapping,
/**
* @deprecated 弃用 请使用@Filter FilterAdapter 替代
*/
Interceptor: _anno.Interceptor,
GetMapping: _anno.GetMapping,
PostMapping: _anno.PostMapping,
PutMapping: _anno.PutMapping,
DeleteMapping: _anno.DeleteMapping,
AppScope: _anno.AppScope,
Validator: _anno.Validator,
RequestParam: _anno.RequestParam,
ResponseBody: _anno.ResponseBody
},
name: 'mvc',
/**
*
* @param {Object} config
*
* @param {Object} config.options 请求配置 @ses{@link bodyParser.Options}
* @param {boolean|undefined} config.options.inflate @ses{@link bodyParser.Options.inflate}
* @param {number|string|undefined} config.options.limit @ses{@link bodyParser.Options.limit}
* @param {boolean} config.options.type @ses{@link bodyParser.Options.type}
*
* @param {Object} config.view 视图配置
* @param {string} config.view.engine 模板引擎 默认ejs
* @param {string} config.view.root 视图目录 默认views
* @param {string} config.view.resource 资源目录 默认public
*
* @param {Object} config.multipart 文件上传配置
* @param {number} config.multipart.maxFields 最大属性个数 默认1000
* @param {number} config.multipart.maxFieldsSize 最大属性限制 默认 2 * 1024 * 1024
* @param {number} config.multipart.maxFilesSize 上传文件限制 默认无
* @param {string} config.multipart.uploadDir 上传临时目录 默认os.tmpdir()
* @param {string} config.multipart.encoding 上传编码 默认utf8
*
* @returns {ControllerAdapter}
*/
launch: function launch(config) {
var log4j = this.log4j,
userDir = this.userDir;
var _config$view = config.view,
view = _config$view === void 0 ? {} : _config$view,
_config$session = config.session,
session = _config$session === void 0 ? false : _config$session,
_config$options = config.options,
options = _config$options === void 0 ? {} : _config$options,
_config$multipart = config.multipart,
multipart = _config$multipart === void 0 ? {} : _config$multipart,
_config$compress = config.compress,
compress = _config$compress === void 0 ? {} : _config$compress,
_config$cookie = config.cookie,
cookie = _config$cookie === void 0 ? {} : _config$cookie;
var _view$engine = view.engine,
engine = _view$engine === void 0 ? 'ejs' : _view$engine,
_view$root = view.root,
root = _view$root === void 0 ? 'views' : _view$root,
_view$resource = view.resource,
resource = _view$resource === void 0 ? 'public' : _view$resource;
var logger = log4j.getLogger("mvc");
app.set('views', path.join(userDir, root));
app.set('view engine', engine);
if (session !== false) {
app.use(require('./session')(session, log4j));
Object.defineProperty(exports, "__esModule", { value: true });
exports.annotation = exports.model = exports.Interceptor = exports.Controller = exports.Validator = exports.Filter = exports.FilterAdapter = exports.Forward = exports.Redirect = exports.View = exports.RestModel = exports.Success = exports.Fail = exports.HttpInterceptor = exports.Param = exports.Scope = exports.Delete = exports.Put = exports.Post = exports.Get = exports.Response = exports.Request = exports.FAIL = exports.SUCCESS = void 0;
const index_1 = require("./controller/index");
const anno_1 = require("./anno");
Object.defineProperty(exports, "Filter", { enumerable: true, get: function () { return anno_1.Filter; } });
Object.defineProperty(exports, "Controller", { enumerable: true, get: function () { return anno_1.Controller; } });
Object.defineProperty(exports, "Interceptor", { enumerable: true, get: function () { return anno_1.Interceptor; } });
Object.defineProperty(exports, "Request", { enumerable: true, get: function () { return anno_1.Request; } });
Object.defineProperty(exports, "Get", { enumerable: true, get: function () { return anno_1.Get; } });
Object.defineProperty(exports, "Post", { enumerable: true, get: function () { return anno_1.Post; } });
Object.defineProperty(exports, "Put", { enumerable: true, get: function () { return anno_1.Put; } });
Object.defineProperty(exports, "Delete", { enumerable: true, get: function () { return anno_1.Delete; } });
Object.defineProperty(exports, "Scope", { enumerable: true, get: function () { return anno_1.Scope; } });
Object.defineProperty(exports, "Validator", { enumerable: true, get: function () { return anno_1.Validator; } });
Object.defineProperty(exports, "Param", { enumerable: true, get: function () { return anno_1.Param; } });
Object.defineProperty(exports, "Response", { enumerable: true, get: function () { return anno_1.Response; } });
const model_1 = require("./model");
Object.defineProperty(exports, "Fail", { enumerable: true, get: function () { return model_1.Fail; } });
Object.defineProperty(exports, "Success", { enumerable: true, get: function () { return model_1.Success; } });
Object.defineProperty(exports, "RestModel", { enumerable: true, get: function () { return model_1.RestModel; } });
Object.defineProperty(exports, "View", { enumerable: true, get: function () { return model_1.View; } });
Object.defineProperty(exports, "Redirect", { enumerable: true, get: function () { return model_1.Redirect; } });
Object.defineProperty(exports, "Forward", { enumerable: true, get: function () { return model_1.Forward; } });
const interceptor_1 = require("./interceptor");
Object.defineProperty(exports, "HttpInterceptor", { enumerable: true, get: function () { return interceptor_1.HttpInterceptor; } });
const filter_1 = require("./controller/filter");
Object.defineProperty(exports, "FilterAdapter", { enumerable: true, get: function () { return filter_1.FilterAdapter; } });
const session_1 = require("./session");
const express = require('express');
const multiparty = require('connect-multiparty');
const path = require('path');
const cookieParser = require('cookie-parser');
const compression = require('compression');
const app = express();
const annotation = {
Controller: anno_1.Controller,
RequestMapping: anno_1.Request,
Interceptor: anno_1.Interceptor,
GetMapping: anno_1.Get,
PostMapping: anno_1.Post,
PutMapping: anno_1.Put,
DeleteMapping: anno_1.Delete,
AppScope: anno_1.Scope,
Validator: anno_1.Validator,
RequestParam: anno_1.Param,
ResponseBody: anno_1.Response
};
exports.annotation = annotation;
const model = { Fail: model_1.Fail, Success: model_1.Success, RestModel: model_1.RestModel, View: model_1.View, Redirect: model_1.Redirect, Forward: model_1.Forward };
exports.model = model;
const SUCCESS = new model_1.Success();
exports.SUCCESS = SUCCESS;
const FAIL = new model_1.Fail();
exports.FAIL = FAIL;
exports.default = {
name: 'mvc',
launch: function (config) {
let { log4j, userDir } = this;
let { view = {}, session = false, options = {}, multipart = {}, compress = {}, cookie = {} } = config;
let { engine = 'ejs', root = 'views', resource = 'public' } = view;
let logger = log4j.getLogger("mvc");
app.set('views', path.join(userDir, root));
app.set('view engine', engine);
if (session !== false) {
app.use((0, session_1.default)(session, log4j));
}
app.use(multiparty(multipart))
.use(compression(compress))
.use(express.json(options))
.use(express.urlencoded(Object.assign({ extended: true }, options)))
.use(express.text(options))
.use(express.raw(options))
.use(cookieParser(cookie.secret, cookie.options))
.use(express.static(path.join(userDir, resource)));
app.locals['props'] = this.props() || {};
return new index_1.default(this, app, config);
}
app.use(multiparty(multipart)).use(compression(compress)).use(express.json(options)).use(express.urlencoded(_objectSpread({
extended: true
}, options))).use(express.text(options)).use(express.raw(options)).use(cookieParser(cookie.secret, cookie.options)).use(express["static"](path.join(userDir, resource))); // 将 props 放入 全局变量
app.locals['props'] = this.props() || {};
return new _controller["default"](this, app, config);
}
};
};
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _model = require("../model");
var _wrapper = _interopRequireDefault(require("../session/wrapper"));
var _anno = require("../anno");
var _error = require("../error");
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var qs = require("querystring");
var InterceptorHandler = /*#__PURE__*/function () {
function InterceptorHandler(context, express) {
var _this = this;
(0, _classCallCheck2["default"])(this, InterceptorHandler);
this.context = context;
this.express = express;
context.getComponent(_anno.Interceptor, true).forEach(function (interceptor) {
_this.handle(interceptor);
});
}
(0, _createClass2["default"])(InterceptorHandler, [{
key: "handle",
value: function handle(interceptor) {
if (!(interceptor instanceof HttpInterceptor)) {
throw new Error("".concat(interceptor.name, " must be extends interceptor.HttpInterceptor"));
}
var express = this.express,
context = this.context;
var logger = context.log4j.getLogger(interceptor.annotation.name);
var path = interceptor.annotation.path;
path.split(',').forEach(function (path) {
logger.info("".concat(interceptor.annotation.name, " intercept [").concat(path, "]"));
express.all(path, function (req, res, next) {
var proxy = new Proxy(interceptor, {
get: function get(target, prop, receiver) {
switch (prop) {
case 'success':
return function (data) {
return res.json(new _model.Success(data));
};
case 'fail':
return function (describe, code) {
return res.json(new _model.Fail(describe, code));
};
case 'view':
return function (path, model) {
res.render(path, _objectSpread({}, model));
};
case 'redirect':
return function (url, params, status) {
if (params) {
url += url.includes('?') ? '&' : '?';
url += qs.stringify(params);
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpInterceptor = exports.InterceptorHandler = void 0;
const model_1 = require("../model");
const wrapper_1 = require("../session/wrapper");
const anno_1 = require("../anno");
const error_1 = require("../error");
let qs = require("querystring");
class InterceptorHandler {
constructor(context, express) {
this.context = context;
this.express = express;
context.getComponent(anno_1.Interceptor, true).forEach(interceptor => {
this.handle(interceptor);
});
}
handle(interceptor) {
if (!(interceptor instanceof HttpInterceptor)) {
throw new Error(`${interceptor.name} must be extends interceptor.HttpInterceptor`);
}
const { express, context } = this;
let { annotation } = interceptor;
let logger = context.log4j.getLogger(annotation.name);
const { path } = annotation;
path.split(',').forEach(path => {
logger.info(`${annotation.name} intercept [${path}]`);
express.all(path, (req, res, next) => {
let proxy = new Proxy(interceptor, {
get: (target, prop, receiver) => {
switch (prop) {
case 'success':
return data => res.json(new model_1.Success(data));
case 'fail':
return (describe, code) => res.json(new model_1.Fail(describe, code));
case 'view':
return (path, model) => {
res.render(path, Object.assign({}, model));
};
case 'redirect':
return (url, params, status) => {
if (params) {
url += url.includes('?') ? '&' : '?';
url += qs.stringify(params);
}
res.redirect(status || 302, url);
};
}
return target[prop];
}
res.redirect(status || 302, url);
};
}
return target[prop];
}
});
var pass = false;
try {
pass = proxy.intercept(req, res, new _wrapper["default"](req.session));
if (pass && pass instanceof Promise) {
pass.then(function (rs) {
if (rs === true || rs === void 0) {
next();
});
let pass = false;
try {
pass = proxy.intercept(req, res, new wrapper_1.default(req.session));
if (pass && pass instanceof Promise) {
pass.then(rs => {
if (rs === true || rs === void 0) {
next();
}
}).catch(err => {
(0, error_1.requestError)(res, err, logger);
});
}
}
})["catch"](function (err) {
(0, _error.requestError)(res, err, logger);
});
}
} catch (err) {
(0, _error.requestError)(res, err, logger);
}
if (pass === true || pass === void 0) {
next();
}
catch (err) {
(0, error_1.requestError)(res, err, logger);
}
if (pass === true || pass === void 0) {
next();
}
});
});
});
}
}]);
return InterceptorHandler;
}();
/**
* @deprecated 弃用 请使用@Filter FilterAdapter 替代
*
* http请求拦截器
*/
var HttpInterceptor = /*#__PURE__*/function () {
function HttpInterceptor() {
(0, _classCallCheck2["default"])(this, HttpInterceptor);
}
(0, _createClass2["default"])(HttpInterceptor, [{
key: "intercept",
value: function intercept(req, res, session) {}
}]);
return HttpInterceptor;
}();
module.exports = function (context, express) {
return new InterceptorHandler(context, express);
}
exports.InterceptorHandler = InterceptorHandler;
class HttpInterceptor {
intercept(req, res, session) {
return;
}
}
exports.HttpInterceptor = HttpInterceptor;
exports.default = (context, express) => {
return new InterceptorHandler(context, express);
};
module.exports.HttpInterceptor = HttpInterceptor;
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _get2 = _interopRequireDefault(require("@babel/runtime/helpers/get"));
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var RestModel = function RestModel() {
(0, _classCallCheck2["default"])(this, RestModel);
};
var Fail = /*#__PURE__*/function (_RestModel) {
(0, _inherits2["default"])(Fail, _RestModel);
var _super = _createSuper(Fail);
function Fail(describe, code) {
var _this;
(0, _classCallCheck2["default"])(this, Fail);
_this = _super.call(this);
_this.success = false;
_this.describe = describe;
_this.code = code;
return _this;
}
return Fail;
}(RestModel);
var Success = /*#__PURE__*/function (_RestModel2) {
(0, _inherits2["default"])(Success, _RestModel2);
var _super2 = _createSuper(Success);
function Success(data) {
var _this2;
(0, _classCallCheck2["default"])(this, Success);
_this2 = _super2.call(this);
_this2.success = true;
_this2.data = data || {};
return _this2;
}
(0, _createClass2["default"])(Success, [{
key: "put",
value: function put(key, value) {
if (Object.prototype.toString.call(this.data) !== '[Object Object]') {
this.data = {};
}
this.data[key] = value;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Redirect = exports.Forward = exports.View = exports.Success = exports.Fail = exports.RestModel = void 0;
class RestModel {
constructor() {
}
}, {
key: "add",
value: function add(value) {
var _this$data;
if (!(this.data instanceof Array)) {
this.data = [];
}
(_this$data = this.data).push.apply(_this$data, (0, _toConsumableArray2["default"])(Array.prototype.slice.call(arguments)));
}
exports.RestModel = RestModel;
class Fail extends RestModel {
constructor(describe, code) {
super();
this.success = false;
this.describe = describe;
this.code = code;
}
}, {
key: "get",
value: function get(key) {
return this.data[key];
}
exports.Fail = Fail;
class Success extends RestModel {
constructor(data) {
super();
this.success = false;
this.success = true;
this.data = data || {};
}
}]);
return Success;
}(RestModel);
var View = /*#__PURE__*/function () {
function View(view, model) {
(0, _classCallCheck2["default"])(this, View);
if (typeof view !== "string") {
model = view;
view = void 0;
put(key, value) {
if (Object.prototype.toString.call(this.data) !== '[Object Object]') {
this.data = {};
}
this.data[key] = value;
}
this.view = view;
this.model = model;
}
(0, _createClass2["default"])(View, [{
key: "signature",
value: function signature() {
return 'view';
add(value) {
if (!(this.data instanceof Array)) {
this.data = [];
}
this.data.push(...Array.prototype.slice.call(arguments));
}
}, {
key: "setAttribute",
value: function setAttribute(key, value) {
this.model[key] = value;
get(key) {
return this.data[key];
}
}, {
key: "getArg",
value: function getArg() {
return [this.view, this.model];
}
exports.Success = Success;
class View {
constructor(view, model) {
if (typeof view !== "string") {
model = view;
view = void 0;
}
this.view = view;
this.model = model;
}
}]);
return View;
}();
var Forward = /*#__PURE__*/function (_View) {
(0, _inherits2["default"])(Forward, _View);
var _super3 = _createSuper(Forward);
function Forward() {
(0, _classCallCheck2["default"])(this, Forward);
return _super3.apply(this, arguments);
}
(0, _createClass2["default"])(Forward, [{
key: "signature",
value: function signature() {
return 'forward';
signature() {
return 'view';
}
}]);
return Forward;
}(View);
var Redirect = /*#__PURE__*/function (_Forward) {
(0, _inherits2["default"])(Redirect, _Forward);
var _super4 = _createSuper(Redirect);
function Redirect(path, params, status) {
var _this3;
(0, _classCallCheck2["default"])(this, Redirect);
_this3 = _super4.call(this, path, params);
_this3.status = status;
return _this3;
}
(0, _createClass2["default"])(Redirect, [{
key: "signature",
value: function signature() {
return 'redirect';
setAttribute(key, value) {
this.model[key] = value;
}
}, {
key: "getArg",
value: function getArg() {
var arg = (0, _get2["default"])((0, _getPrototypeOf2["default"])(Redirect.prototype), "getArg", this).call(this);
arg.push(this.status);
return arg;
getArg() {
return [this.view, this.model];
}
}]);
return Redirect;
}(Forward);
module.exports = {
Fail: Fail,
Success: Success,
RestModel: RestModel,
View: View,
Redirect: Redirect,
Forward: Forward
};
}
exports.View = View;
class Forward extends View {
signature() {
return 'forward';
}
}
exports.Forward = Forward;
class Redirect extends Forward {
constructor(path, params, status) {
super(path, params);
this.status = status;
}
signature() {
return 'redirect';
}
getArg() {
let arg = super.getArg();
arg.push(this.status);
return arg;
}
}
exports.Redirect = Redirect;
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var session = require("express-session");
var defaultCookie = {
maxAge: 1800 * 1000,
path: '/',
httpOnly: true,
secure: false
Object.defineProperty(exports, "__esModule", { value: true });
const session = require("express-session");
const defaultCookie = {
maxAge: 1800 * 1000,
path: '/',
httpOnly: true,
secure: false
};
var uuid = require('uuid');
var defaultConfig = {
redis: false,
rolling: false,
saveUninitialized: true,
resave: true,
name: 'vweb.sid',
secret: 'vweb.secret',
genid: uuid.v4
let uuid = require('uuid');
const defaultConfig = {
redis: false,
rolling: false,
saveUninitialized: true,
resave: true,
name: 'vweb.sid',
secret: 'vweb.secret',
genid: uuid.v4
};
/**
* session
* @param config
* @param log4j
* @returns {*}
*/
module.exports = function (config, log4j) {
config.cookie = Object.assign(defaultCookie, config.cookie);
var options = Object.assign(defaultConfig, config);
if (options.redis) {
//如果配置了redis 使用redis存储session
var logger = log4j.getLogger('redis.session');
var redis = require('redis');
var RedisStore = require('connect-redis')(session);
var _options$redis = options.redis,
_options$redis$host = _options$redis.host,
host = _options$redis$host === void 0 ? 'localhost' : _options$redis$host,
_options$redis$port = _options$redis.port,
port = _options$redis$port === void 0 ? 6379 : _options$redis$port,
_options$redis$databa = _options$redis.database,
database = _options$redis$databa === void 0 ? 0 : _options$redis$databa,
password = _options$redis.password,
namespace = _options$redis.namespace;
var redisClient = redis.createClient({
host: host,
port: port,
password: password,
db: database,
prefix: namespace
});
options.store = new RedisStore(_objectSpread({
client: redisClient,
prefix: "".concat(config.prefix || 'session', ":"),
ttl: options.cookie.maxAge / 1000,
logErrors: function logErrors(error) {
logger.error(error);
}
}, options.redis));
}
return session(options);
};
function default_1(config, log4j) {
config.cookie = Object.assign(defaultCookie, config.cookie);
const options = Object.assign(defaultConfig, config);
if (options.redis) {
const logger = log4j.getLogger('redis.session');
const redis = require('redis');
const RedisStore = require('connect-redis')(session);
const { host = 'localhost', port = 6379, database = 0, password, namespace } = options.redis;
let redisClient = redis.createClient({
host, port, password, db: database, prefix: namespace
});
options.store = new RedisStore(Object.assign({ client: redisClient, prefix: `${config.prefix || 'session'}:`, ttl: options.cookie.maxAge / 1000, logErrors: function (error) {
logger.error(error);
} }, options.redis));
}
return session(options);
}
exports.default = default_1;
;
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _KEYS$ALL = {
KEYS: '$keys$',
ALL: '$all$'
},
KEYS = _KEYS$ALL.KEYS,
ALL = _KEYS$ALL.ALL;
/**
* session 操作类
*/
var Wrapper = /*#__PURE__*/function () {
function Wrapper(session) {
(0, _classCallCheck2["default"])(this, Wrapper);
if (!session) session = {
virtual: true
};
var _session = session,
attributes = _session.attributes;
if (!attributes) session.attributes = {};
this.id = session.id;
this.attributes = new Proxy(session.attributes, {
set: function set(target, prop, value, proxy) {
return Reflect.set(target, prop, value, proxy);
},
get: function get(target, prop, proxy) {
if (prop === KEYS) return Object.keys(target);
if (prop === ALL) return target;else return Reflect.get(target, prop, proxy);
}
});
}
(0, _createClass2["default"])(Wrapper, [{
key: "setAttribute",
value: function setAttribute(name, object) {
this.attributes[name] = object;
Object.defineProperty(exports, "__esModule", { value: true });
const { KEYS, ALL } = {
KEYS: '$keys$',
ALL: '$all$',
};
class Wrapper {
constructor(session) {
if (!session)
session = { virtual: true };
const { attributes } = session;
if (!attributes)
session.attributes = {};
this.id = session.id;
this.attributes = new Proxy(session.attributes, {
set(target, prop, value, proxy) {
return Reflect.set(target, prop, value, proxy);
},
get(target, prop, proxy) {
if (prop === KEYS)
return Object.keys(target);
if (prop === ALL)
return target;
else
return Reflect.get(target, prop, proxy);
}
});
}
}, {
key: "getAttribute",
value: function getAttribute(name) {
return this.attributes[name];
setAttribute(name, object) {
this.attributes[name] = object;
}
}, {
key: "getAttributeNames",
value: function getAttributeNames() {
return this.attributes[KEYS];
getAttribute(name) {
return this.attributes[name];
}
}, {
key: "getAttributes",
value: function getAttributes() {
return this.attributes[ALL];
getAttributeNames() {
return this.attributes[KEYS];
}
}]);
return Wrapper;
}();
var _default = Wrapper;
exports["default"] = _default;
getAttributes() {
return this.attributes[ALL];
}
}
exports.default = Wrapper;
{
"name": "vweb-mvc",
"version": "1.0.83",
"version": "1.1.1",
"description": "mvc ",
"main": "./lib/index",
"files": [
"lib/",
"src/"
"lib/"
],
"scripts": {
"test": "node bin/app.js",
"build": "babel src --out-dir lib/",
"build": "tsc --build tsconfig.json",
"run": "babel src --out-dir lib/ && node bin/app.js"

@@ -37,5 +36,6 @@ },

"redis": "^3.1.2",
"vweb-core": "^1.1.24"
"vweb-core": "^1.1.28"
},
"dependencies": {
"@types/node": "^16.11.12",
"compression": "^1.7.4",

@@ -42,0 +42,0 @@ "connect-multiparty": "^2.2.0",

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc