@azteam/express 1.2.280 → 1.2.282

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports["default"] = void 0;
7
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
8
+ function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
9
+ function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
10
+ var Controller = /*#__PURE__*/function () {
11
+ function Controller() {
12
+ var pathName = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
13
+ var repository = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
14
+ _classCallCheck(this, Controller);
15
+ this.pathName = pathName;
16
+ this.repository = repository;
17
+ }
18
+ _createClass(Controller, [{
19
+ key: "publicRouter",
20
+ value: function publicRouter() {
21
+ var child = this;
22
+ var result = [];
23
+ while (Object.getPrototypeOf(child.__proto__)) {
24
+ var data = Object.getOwnPropertyNames(Object.getPrototypeOf(child));
25
+ data.map(function (methodName) {
26
+ var matches = methodName.match(/^(get|post|put|patch|delete)/);
27
+ if (matches) {
28
+ var path = '/';
29
+ if (methodName.endsWith('Public')) {
30
+ path += 'public';
31
+ } else if (methodName.endsWith('Trash')) {
32
+ path += 'trash';
33
+ }
34
+ result.push({
35
+ type: matches[0],
36
+ name: methodName,
37
+ path: path
38
+ });
39
+ }
40
+ return true;
41
+ });
42
+ child = child.__proto__;
43
+ }
44
+ return result;
45
+ }
46
+ }]);
47
+ return Controller;
48
+ }();
49
+ var _default = Controller;
50
+ exports["default"] = _default;
package/lib/Server.js ADDED
@@ -0,0 +1,427 @@
1
+ "use strict";
2
+
3
+ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports["default"] = void 0;
8
+ var _lodash = _interopRequireDefault(require("lodash"));
9
+ var _fs = _interopRequireDefault(require("fs"));
10
+ var _path = _interopRequireDefault(require("path"));
11
+ var _http = _interopRequireDefault(require("http"));
12
+ var _express = _interopRequireDefault(require("express"));
13
+ var _helmet = _interopRequireDefault(require("helmet"));
14
+ var _methodOverride = _interopRequireDefault(require("method-override"));
15
+ var _bodyParser = _interopRequireDefault(require("body-parser"));
16
+ var _cookieParser = _interopRequireDefault(require("cookie-parser"));
17
+ var _morgan = _interopRequireDefault(require("morgan"));
18
+ var _cors = _interopRequireDefault(require("cors"));
19
+ var _psl = _interopRequireDefault(require("psl"));
20
+ require("express-async-errors");
21
+ var _error = require("@azteam/error");
22
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
23
+ function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return generator._invoke = function (innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; }(innerFn, self, context), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; this._invoke = function (method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); }; } function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (undefined === method) { if (context.delegate = null, "throw" === context.method) { if (delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel; context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) { if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; } return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (object) { var keys = []; for (var key in object) { keys.push(key); } return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) { "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); } }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; }
24
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
25
+ function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
26
+ function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
27
+ function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
28
+ 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); }
29
+ function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
30
+ function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
31
+ 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; }
32
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
33
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
34
+ function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
35
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
36
+ function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
37
+ function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
38
+ var RES_TYPE = {
39
+ ARRAY: 'ARRAY',
40
+ OBJECT: 'OBJECT',
41
+ DOCS: 'DOCS'
42
+ };
43
+ function omitItem(item, guard, allow) {
44
+ var guardFields = guard;
45
+ var itemFields = item;
46
+ if (_lodash["default"].isArray(guardFields)) {
47
+ guardFields = _lodash["default"].difference(guardFields, allow);
48
+ }
49
+ if (itemFields.toJSON) {
50
+ itemFields = item.toJSON();
51
+ }
52
+ if (_lodash["default"].isObject(itemFields)) {
53
+ if (guardFields === '*') {
54
+ return _lodash["default"].pick(itemFields, allow);
55
+ }
56
+ return _lodash["default"].omit(itemFields, guardFields);
57
+ }
58
+ return itemFields;
59
+ }
60
+ var Server = /*#__PURE__*/function () {
61
+ function Server() {
62
+ var currentDir = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
63
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
64
+ _classCallCheck(this, Server);
65
+ this.redis = null;
66
+ this.options = _objectSpread({
67
+ isAllowEmptyOrigin: true
68
+ }, options);
69
+ this.cookieOption = {
70
+ domain: null,
71
+ path: '/',
72
+ secure: process.env.NODE_ENV !== 'development',
73
+ httpOnly: true,
74
+ signed: true,
75
+ sameSite: 'Lax'
76
+ };
77
+ this.middlewares = [];
78
+ this.controllers = [];
79
+ this.whiteList = [];
80
+ this.debug = process.env.NODE_ENV === 'development';
81
+ this.initController(currentDir);
82
+ }
83
+ _createClass(Server, [{
84
+ key: "setRedis",
85
+ value: function setRedis(redis) {
86
+ this.redis = redis;
87
+ return this;
88
+ }
89
+ }, {
90
+ key: "setCookieOption",
91
+ value: function setCookieOption(cookieOption) {
92
+ this.cookieOption = _objectSpread(_objectSpread({}, this.cookieOption), cookieOption);
93
+ return this;
94
+ }
95
+ }, {
96
+ key: "setCallbackError",
97
+ value: function setCallbackError() {
98
+ var callback = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
99
+ this.callbackError = callback;
100
+ return this;
101
+ }
102
+ }, {
103
+ key: "setWhiteList",
104
+ value: function setWhiteList(whiteList) {
105
+ this.whiteList = whiteList;
106
+ return this;
107
+ }
108
+ }, {
109
+ key: "setDebug",
110
+ value: function setDebug(debug) {
111
+ this.debug = debug;
112
+ return this;
113
+ }
114
+ }, {
115
+ key: "addController",
116
+ value: function addController(name, version, controller) {
117
+ this.controllers.push({
118
+ name: name,
119
+ version: version,
120
+ controller: controller
121
+ });
122
+ return this;
123
+ }
124
+ }, {
125
+ key: "initController",
126
+ value: function initController(apiDir) {
127
+ if (apiDir) {
128
+ var controllerDirs = _fs["default"].readdirSync(apiDir);
129
+ for (var i = 0; i < controllerDirs.length; i += 1) {
130
+ var dirName = controllerDirs[i];
131
+ if (_fs["default"].statSync("".concat(apiDir, "/").concat(dirName)).isDirectory()) {
132
+ var versionDirs = _fs["default"].readdirSync("".concat(apiDir, "/").concat(dirName));
133
+ for (var j = 0; j < versionDirs.length; j += 1) {
134
+ var versionName = versionDirs[j];
135
+
136
+ // eslint-disable-next-line global-require,import/no-dynamic-require
137
+ var controller = require("".concat(apiDir, "/").concat(dirName, "/").concat(versionName, "/controller"))["default"];
138
+ this.addController(dirName, versionName, controller);
139
+ }
140
+ }
141
+ }
142
+ }
143
+ return this;
144
+ }
145
+ }, {
146
+ key: "addGlobalMiddleware",
147
+ value: function addGlobalMiddleware(middleware) {
148
+ this.middlewares.push(middleware);
149
+ return this;
150
+ }
151
+ }, {
152
+ key: "startAPI",
153
+ value: function startAPI(port) {
154
+ var _this3 = this;
155
+ if (!_lodash["default"].isEmpty(this.controllers)) {
156
+ var WHITE_LIST = this.whiteList;
157
+ var COOKIE_OPTION = this.cookieOption;
158
+ var isAllowEmptyOrigin = this.options.isAllowEmptyOrigin;
159
+ var app = (0, _express["default"])();
160
+ app.use((0, _helmet["default"])({
161
+ frameguard: false
162
+ }));
163
+ app.use((0, _methodOverride["default"])());
164
+ app.use(_bodyParser["default"].urlencoded({
165
+ limit: '5mb',
166
+ extended: true
167
+ }));
168
+ app.use(_bodyParser["default"].json({
169
+ limit: '5mb'
170
+ }));
171
+ app.set('trust proxy', 1);
172
+ app.use((0, _cookieParser["default"])(process.env.SECRET_KEY));
173
+ app.use((0, _cors["default"])(function (req, callback) {
174
+ var origin = req.header('Origin');
175
+ var authorization = req.header('Authorization');
176
+ var appSecret = req.header('x-app-secret');
177
+ var agent = req.header('User-Agent');
178
+ var error = null;
179
+ if (!authorization && !appSecret && !agent.startsWith('toda')) {
180
+ if (!origin) {
181
+ if (!isAllowEmptyOrigin) {
182
+ error = new _error.ErrorException(_error.CORS, "Not allowed by CORS");
183
+ }
184
+ } else if (!WHITE_LIST.some(function (re) {
185
+ return origin.endsWith(re);
186
+ })) {
187
+ error = new _error.ErrorException(_error.CORS, "".concat(origin, " Not allowed by CORS"));
188
+ }
189
+ }
190
+ callback(error, {
191
+ credentials: true,
192
+ origin: true
193
+ });
194
+ }));
195
+ if (this.debug) {
196
+ app.use((0, _morgan["default"])('dev'));
197
+ }
198
+ app.get('/robots.txt', function (req, res) {
199
+ res.type('text/plain');
200
+ res.send('User-agent: *\nDisallow: /');
201
+ });
202
+ app.get('/favicon.ico', function (req, res) {
203
+ return res.status(204).json({});
204
+ });
205
+ var redis = this.redis;
206
+ if (redis) {
207
+ app.request.redis = redis;
208
+ app.response.redis = redis;
209
+ }
210
+ app.response.error = function (code) {
211
+ var errors = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
212
+ throw new _error.ErrorException(code, errors);
213
+ };
214
+ app.response.success = function () {
215
+ var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
216
+ var guard = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
217
+ var allow = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
218
+ var guardData = data;
219
+ if (data) {
220
+ var resType = null;
221
+ if (_lodash["default"].isArray(data)) {
222
+ resType = RES_TYPE.ARRAY;
223
+ } else if (_lodash["default"].isObject(data)) {
224
+ resType = RES_TYPE.OBJECT;
225
+ if (data.docs) {
226
+ resType = RES_TYPE.DOCS;
227
+ }
228
+ }
229
+ var responseGuard = guard;
230
+ var responseAllows = allow;
231
+ if (_lodash["default"].isArray(guard)) {
232
+ responseGuard = [].concat(_toConsumableArray(guard), ['__v', '_id', 'deleted_at', 'updated_at', 'created_id', 'modified_id', 'resource', 'is_processing', 'priority']);
233
+ }
234
+ if (resType === RES_TYPE.DOCS) {
235
+ guardData.docs = _lodash["default"].map(data.docs, function (item) {
236
+ return omitItem(item, responseGuard, responseAllows);
237
+ });
238
+ } else if (resType === RES_TYPE.ARRAY) {
239
+ guardData = _lodash["default"].map(data, function (item) {
240
+ return omitItem(item, responseGuard, responseAllows);
241
+ });
242
+ } else if (resType === RES_TYPE.OBJECT) {
243
+ guardData = omitItem(data, responseGuard, responseAllows);
244
+ }
245
+ }
246
+ var resData = {
247
+ success: true,
248
+ data: guardData,
249
+ options: this.resOptions
250
+ };
251
+ if (this.redis && this.cache) {
252
+ this.redis.set(this.cache.key, resData, this.cache.ttl);
253
+ }
254
+ return this.json(resData);
255
+ };
256
+ app.response.cleanCookie = function (data) {
257
+ var _this = this;
258
+ _lodash["default"].map(data, function (name) {
259
+ _this.clearCookie(name, {
260
+ domain: COOKIE_OPTION.domain
261
+ });
262
+ });
263
+ };
264
+ app.response.addCookie = function (data) {
265
+ var _this2 = this;
266
+ _lodash["default"].map(data, function (value, key) {
267
+ var maxAge = 86400000 * 365; // 1 year
268
+ _this2.cookie(key, value, _objectSpread(_objectSpread({}, COOKIE_OPTION), {}, {
269
+ maxAge: maxAge,
270
+ expires: new Date(Date.now() + maxAge)
271
+ }));
272
+ });
273
+ };
274
+ app.use(function (req, res, next) {
275
+ delete res.cache;
276
+ var origin = req.get('Origin');
277
+ req.rootOrigin = origin ? _psl["default"].parse(origin).domain : null;
278
+ req.trackDevice = {
279
+ ip: req.headers['x-forwarded-for'] || req.headers['x-real-ip'] || req.ip,
280
+ device: req.get('X-DEVICE') || req.get('User-Agent'),
281
+ device_id: req.get('X-DEVICE-ID') || 'web',
282
+ os: req.get('X-OS') || 'web'
283
+ };
284
+ next();
285
+ });
286
+ _lodash["default"].map(this.middlewares, function (middleware) {
287
+ app.use(middleware);
288
+ });
289
+ var msg = [];
290
+ _lodash["default"].map(this.controllers, function (data) {
291
+ var controller = data.controller;
292
+ var controllerName = data.name;
293
+ var controllerVersion = data.version;
294
+ var listPublicRouter = controller.publicRouter();
295
+ _lodash["default"].map(listPublicRouter, function (method) {
296
+ var name = method.name,
297
+ type = method.type;
298
+ var router = controller[name]();
299
+ if (!router.disabled) {
300
+ router.path = "/".concat(method.path, "/").concat(router.path);
301
+ router.path = controller.pathName ? "/".concat(controller.pathName).concat(router.path) : router.path;
302
+ router.path = controllerVersion.startsWith('v') ? "/".concat(controllerVersion).concat(router.path) : router.path;
303
+ router.path = _path["default"].normalize(router.path);
304
+ msg.push({
305
+ controller: controllerName,
306
+ version: controllerVersion,
307
+ type: type,
308
+ method: name,
309
+ path: router.path
310
+ });
311
+ app[type].apply(app, [router.path].concat(_toConsumableArray(router.method)));
312
+ }
313
+ });
314
+ });
315
+ console.table(msg);
316
+ app.all('/', /*#__PURE__*/function () {
317
+ var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req, res) {
318
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
319
+ while (1) {
320
+ switch (_context.prev = _context.next) {
321
+ case 0:
322
+ return _context.abrupt("return", res.success('welcome'));
323
+ case 1:
324
+ case "end":
325
+ return _context.stop();
326
+ }
327
+ }
328
+ }, _callee);
329
+ }));
330
+ return function (_x, _x2) {
331
+ return _ref.apply(this, arguments);
332
+ };
333
+ }());
334
+ app.get('/track', /*#__PURE__*/function () {
335
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(req, res) {
336
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
337
+ while (1) {
338
+ switch (_context2.prev = _context2.next) {
339
+ case 0:
340
+ return _context2.abrupt("return", res.success(_objectSpread(_objectSpread({}, req.trackDevice), {}, {
341
+ host: req.hostname,
342
+ origin: req.get('origin')
343
+ })));
344
+ case 1:
345
+ case "end":
346
+ return _context2.stop();
347
+ }
348
+ }
349
+ }, _callee2);
350
+ }));
351
+ return function (_x3, _x4) {
352
+ return _ref2.apply(this, arguments);
353
+ };
354
+ }());
355
+ app.use(function (req, res) {
356
+ throw new _error.ErrorException(_error.NOT_FOUND);
357
+ });
358
+ app.use(function (err, req, res, next) {
359
+ var error = (0, _error.errorCatch)(err);
360
+ if (process.env.NODE_ENV === 'development') {
361
+ console.log(error.errors);
362
+ } else if (error.errors[0].code === _error.UNKNOWN) {
363
+ console.error(req.originalUrl, err);
364
+ }
365
+ if (_this3.callbackError) {
366
+ _this3.callbackError(error, req.originalUrl);
367
+ }
368
+ return res.status(error.status).json({
369
+ success: false,
370
+ errors: error.errors
371
+ });
372
+ });
373
+ var server = _http["default"].Server(app);
374
+ server.on('listening', function () {
375
+ _this3._alert('listening', "Server start at http://localhost:".concat(server.address().port));
376
+ });
377
+ server.on('error', function (error) {
378
+ if (error.syscall !== 'listen') {
379
+ throw error;
380
+ }
381
+ var bind = typeof port === 'string' ? "Pipe ".concat(port) : "Port ".concat(port);
382
+ switch (error.code) {
383
+ case 'EACCES':
384
+ _this3._alert('EACCES', "".concat(bind, " requires elevated privileges"));
385
+ process.exit(1);
386
+ break;
387
+ case 'EADDRINUSE':
388
+ _this3._alert('EACCES', "".concat(bind, " is already in use"));
389
+ process.exit(1);
390
+ break;
391
+ default:
392
+ throw error;
393
+ }
394
+ });
395
+ server.listen(port);
396
+ return server;
397
+ }
398
+ throw new Error('No controllers in use API');
399
+ }
400
+ }, {
401
+ key: "startSocket",
402
+ value: function startSocket(port) {
403
+ if (!_lodash["default"].isEmpty(this.controllers)) {
404
+ return this;
405
+ }
406
+ throw new Error('No controllers in use SOCKET');
407
+ }
408
+ }, {
409
+ key: "setAlertCallback",
410
+ value: function setAlertCallback(callback) {
411
+ this.alertCallback = callback;
412
+ return this;
413
+ }
414
+ }, {
415
+ key: "_alert",
416
+ value: function _alert(status, msg) {
417
+ if (typeof this.alertCallback === 'function') {
418
+ this.alertCallback(status, msg);
419
+ } else {
420
+ console.log(status, msg);
421
+ }
422
+ }
423
+ }]);
424
+ return Server;
425
+ }();
426
+ var _default = Server;
427
+ exports["default"] = _default;