@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.
- package/lib/AdminController.js +707 -0
- package/lib/Controller.js +50 -0
- package/lib/Server.js +427 -0
- package/lib/SocketServer.js +226 -0
- package/lib/constant.js +19 -0
- package/lib/index.js +64 -0
- package/lib/middleware/adminRoleMiddleware.js +13 -0
- package/lib/middleware/authMiddleware.js +97 -0
- package/lib/middleware/cacheMiddleware.js +80 -0
- package/lib/middleware/etagMiddleware.js +52 -0
- package/lib/middleware/index.js +83 -0
- package/lib/middleware/limitRequestMiddleware.js +25 -0
- package/lib/middleware/paginateMiddleware.js +147 -0
- package/lib/middleware/roleMiddleware.js +53 -0
- package/lib/middleware/signMiddleware.js +45 -0
- package/lib/middleware/systemRoleMiddleware.js +12 -0
- package/lib/middleware/validateMiddleware.js +81 -0
- package/lib/middleware/verifyGoogleAppMiddleware.js +39 -0
- package/lib/validate.js +251 -0
- package/package.json +5 -6
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports["default"] = void 0;
|
|
7
|
+
var _fs = _interopRequireDefault(require("fs"));
|
|
8
|
+
var _http = _interopRequireDefault(require("http"));
|
|
9
|
+
var _express = _interopRequireDefault(require("express"));
|
|
10
|
+
var _socket = _interopRequireDefault(require("socket.io"));
|
|
11
|
+
var _bodyParser = _interopRequireDefault(require("body-parser"));
|
|
12
|
+
var _cookieParser = _interopRequireDefault(require("cookie-parser"));
|
|
13
|
+
var _socket2 = _interopRequireDefault(require("socket.io-redis"));
|
|
14
|
+
var _lodash = _interopRequireDefault(require("lodash"));
|
|
15
|
+
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
|
|
16
|
+
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
|
|
17
|
+
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."); }
|
|
18
|
+
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
|
|
19
|
+
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
|
|
20
|
+
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; } } }; }
|
|
21
|
+
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); }
|
|
22
|
+
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; }
|
|
23
|
+
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; }
|
|
24
|
+
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; }
|
|
25
|
+
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; }
|
|
26
|
+
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
|
27
|
+
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); } }
|
|
28
|
+
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
|
|
29
|
+
var wrap = function wrap(middleware) {
|
|
30
|
+
return function (socket, next) {
|
|
31
|
+
return middleware(socket.request, {}, next);
|
|
32
|
+
};
|
|
33
|
+
};
|
|
34
|
+
var SocketServer = /*#__PURE__*/function () {
|
|
35
|
+
function SocketServer() {
|
|
36
|
+
var currentDir = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
|
|
37
|
+
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
|
38
|
+
_classCallCheck(this, SocketServer);
|
|
39
|
+
this.options = _objectSpread({
|
|
40
|
+
redisConfig: null
|
|
41
|
+
}, options);
|
|
42
|
+
this.middlewares = [];
|
|
43
|
+
this.controllers = [];
|
|
44
|
+
this.whiteList = [];
|
|
45
|
+
this.debug = process.env.NODE_ENV === 'development';
|
|
46
|
+
this.initController(currentDir);
|
|
47
|
+
}
|
|
48
|
+
_createClass(SocketServer, [{
|
|
49
|
+
key: "setCallbackError",
|
|
50
|
+
value: function setCallbackError() {
|
|
51
|
+
var callback = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
|
|
52
|
+
this.callbackError = callback;
|
|
53
|
+
return this;
|
|
54
|
+
}
|
|
55
|
+
}, {
|
|
56
|
+
key: "setWhiteList",
|
|
57
|
+
value: function setWhiteList(whiteList) {
|
|
58
|
+
this.whiteList = whiteList;
|
|
59
|
+
return this;
|
|
60
|
+
}
|
|
61
|
+
}, {
|
|
62
|
+
key: "setDebug",
|
|
63
|
+
value: function setDebug(debug) {
|
|
64
|
+
this.debug = debug;
|
|
65
|
+
return this;
|
|
66
|
+
}
|
|
67
|
+
}, {
|
|
68
|
+
key: "addController",
|
|
69
|
+
value: function addController(name, version, controller) {
|
|
70
|
+
this.controllers.push({
|
|
71
|
+
name: name,
|
|
72
|
+
version: version,
|
|
73
|
+
controller: controller
|
|
74
|
+
});
|
|
75
|
+
return this;
|
|
76
|
+
}
|
|
77
|
+
}, {
|
|
78
|
+
key: "initController",
|
|
79
|
+
value: function initController(apiDir) {
|
|
80
|
+
if (apiDir) {
|
|
81
|
+
var controllerDirs = _fs["default"].readdirSync(apiDir);
|
|
82
|
+
var _iterator = _createForOfIteratorHelper(controllerDirs),
|
|
83
|
+
_step;
|
|
84
|
+
try {
|
|
85
|
+
for (_iterator.s(); !(_step = _iterator.n()).done;) {
|
|
86
|
+
var dirName = _step.value;
|
|
87
|
+
if (_fs["default"].statSync("".concat(apiDir, "/").concat(dirName)).isDirectory()) {
|
|
88
|
+
var versionDirs = _fs["default"].readdirSync("".concat(apiDir, "/").concat(dirName));
|
|
89
|
+
var _iterator2 = _createForOfIteratorHelper(versionDirs),
|
|
90
|
+
_step2;
|
|
91
|
+
try {
|
|
92
|
+
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
|
|
93
|
+
var versionName = _step2.value;
|
|
94
|
+
// eslint-disable-next-line import/no-dynamic-require,global-require
|
|
95
|
+
var controller = require("".concat(apiDir, "/").concat(dirName, "/").concat(versionName, "/controller"))["default"];
|
|
96
|
+
this.addController(dirName, versionName, controller);
|
|
97
|
+
}
|
|
98
|
+
} catch (err) {
|
|
99
|
+
_iterator2.e(err);
|
|
100
|
+
} finally {
|
|
101
|
+
_iterator2.f();
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
} catch (err) {
|
|
106
|
+
_iterator.e(err);
|
|
107
|
+
} finally {
|
|
108
|
+
_iterator.f();
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return this;
|
|
112
|
+
}
|
|
113
|
+
}, {
|
|
114
|
+
key: "addGlobalMiddleware",
|
|
115
|
+
value: function addGlobalMiddleware(middleware) {
|
|
116
|
+
this.middlewares.push(middleware);
|
|
117
|
+
return this;
|
|
118
|
+
}
|
|
119
|
+
}, {
|
|
120
|
+
key: "startPort",
|
|
121
|
+
value: function startPort(port) {
|
|
122
|
+
var _this = this;
|
|
123
|
+
if (!_lodash["default"].isEmpty(this.controllers)) {
|
|
124
|
+
var WHITE_LIST = this.whiteList;
|
|
125
|
+
var server = _http["default"].Server((0, _express["default"])());
|
|
126
|
+
var io = (0, _socket["default"])(server, {
|
|
127
|
+
wsEngine: 'eiows',
|
|
128
|
+
perMessageDeflate: {
|
|
129
|
+
threshold: 32768
|
|
130
|
+
},
|
|
131
|
+
cors: {
|
|
132
|
+
credentials: true,
|
|
133
|
+
origin: function origin(_origin, callback) {
|
|
134
|
+
if (!_origin || !WHITE_LIST.length || WHITE_LIST.some(function (re) {
|
|
135
|
+
return _origin.endsWith(re);
|
|
136
|
+
})) {
|
|
137
|
+
callback(null, true);
|
|
138
|
+
} else {
|
|
139
|
+
callback(new Error("".concat(_origin, " Not allowed by CORS")));
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
});
|
|
144
|
+
if (this.options.redisConfig) {
|
|
145
|
+
io.adapter((0, _socket2["default"])(this.options.redisConfig));
|
|
146
|
+
}
|
|
147
|
+
var msg = [];
|
|
148
|
+
_lodash["default"].map(this.controllers, function (obj) {
|
|
149
|
+
var controller = obj.controller;
|
|
150
|
+
_lodash["default"].map(controller, function (item, key) {
|
|
151
|
+
item.path = obj.version.startsWith('v') ? "/".concat(obj.version).concat(item.path) : item.path;
|
|
152
|
+
var nsp = io.of(item.path);
|
|
153
|
+
var middlewares = [].concat(_toConsumableArray(_this.middlewares), _toConsumableArray(item.middlewares || []));
|
|
154
|
+
nsp.use(wrap(_bodyParser["default"].urlencoded({
|
|
155
|
+
limit: '5mb',
|
|
156
|
+
extended: true
|
|
157
|
+
})));
|
|
158
|
+
nsp.use(wrap(_bodyParser["default"].json({
|
|
159
|
+
limit: '5mb'
|
|
160
|
+
})));
|
|
161
|
+
nsp.use(wrap((0, _cookieParser["default"])(process.env.SECRET_KEY)));
|
|
162
|
+
_lodash["default"].map(middlewares, function (middleware) {
|
|
163
|
+
nsp.use(wrap(middleware));
|
|
164
|
+
});
|
|
165
|
+
if (item.schedule) {
|
|
166
|
+
item.schedule(io);
|
|
167
|
+
}
|
|
168
|
+
if (item.connection) {
|
|
169
|
+
nsp.on('connection', function (socket) {
|
|
170
|
+
item.connection(io, socket);
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
msg.push({
|
|
174
|
+
controller: obj.name,
|
|
175
|
+
version: obj.version,
|
|
176
|
+
path: item.path
|
|
177
|
+
});
|
|
178
|
+
});
|
|
179
|
+
});
|
|
180
|
+
console.table(msg);
|
|
181
|
+
server.on('listening', function () {
|
|
182
|
+
_this._alert('listening', "Server start at http://localhost:".concat(server.address().port));
|
|
183
|
+
});
|
|
184
|
+
server.on('error', function (error) {
|
|
185
|
+
if (error.syscall !== 'listen') {
|
|
186
|
+
throw error;
|
|
187
|
+
}
|
|
188
|
+
var bind = typeof port === 'string' ? "Pipe ".concat(port) : "Port ".concat(port);
|
|
189
|
+
switch (error.code) {
|
|
190
|
+
case 'EACCES':
|
|
191
|
+
_this._alert('EACCES', "".concat(bind, " requires elevated privileges"));
|
|
192
|
+
process.exit(1);
|
|
193
|
+
break;
|
|
194
|
+
case 'EADDRINUSE':
|
|
195
|
+
_this._alert('EACCES', "".concat(bind, " is already in use"));
|
|
196
|
+
process.exit(1);
|
|
197
|
+
break;
|
|
198
|
+
default:
|
|
199
|
+
throw error;
|
|
200
|
+
}
|
|
201
|
+
});
|
|
202
|
+
server.listen(port);
|
|
203
|
+
return server;
|
|
204
|
+
}
|
|
205
|
+
throw new Error('No controllers in use');
|
|
206
|
+
}
|
|
207
|
+
}, {
|
|
208
|
+
key: "setAlertCallback",
|
|
209
|
+
value: function setAlertCallback(callback) {
|
|
210
|
+
this.alertCallback = callback;
|
|
211
|
+
return this;
|
|
212
|
+
}
|
|
213
|
+
}, {
|
|
214
|
+
key: "_alert",
|
|
215
|
+
value: function _alert(status, msg) {
|
|
216
|
+
if (typeof this.alertCallback === 'function') {
|
|
217
|
+
this.alertCallback(status, msg);
|
|
218
|
+
} else {
|
|
219
|
+
console.log(status, msg);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}]);
|
|
223
|
+
return SocketServer;
|
|
224
|
+
}();
|
|
225
|
+
var _default = SocketServer;
|
|
226
|
+
exports["default"] = _default;
|
package/lib/constant.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports.USER_LEVEL = exports.REQUEST_TYPE = void 0;
|
|
7
|
+
var REQUEST_TYPE = {
|
|
8
|
+
PARAMS: 'params',
|
|
9
|
+
BODY: 'body',
|
|
10
|
+
QUERY: 'query'
|
|
11
|
+
};
|
|
12
|
+
exports.REQUEST_TYPE = REQUEST_TYPE;
|
|
13
|
+
var USER_LEVEL = {
|
|
14
|
+
GUESS: 0,
|
|
15
|
+
USER: 1,
|
|
16
|
+
ADMIN: 50,
|
|
17
|
+
SYSTEM: 100
|
|
18
|
+
};
|
|
19
|
+
exports.USER_LEVEL = USER_LEVEL;
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
var _exportNames = {
|
|
7
|
+
Controller: true,
|
|
8
|
+
AdminController: true
|
|
9
|
+
};
|
|
10
|
+
Object.defineProperty(exports, "AdminController", {
|
|
11
|
+
enumerable: true,
|
|
12
|
+
get: function get() {
|
|
13
|
+
return _AdminController["default"];
|
|
14
|
+
}
|
|
15
|
+
});
|
|
16
|
+
Object.defineProperty(exports, "Controller", {
|
|
17
|
+
enumerable: true,
|
|
18
|
+
get: function get() {
|
|
19
|
+
return _Controller["default"];
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
exports["default"] = void 0;
|
|
23
|
+
var _Server = _interopRequireDefault(require("./Server"));
|
|
24
|
+
var _Controller = _interopRequireDefault(require("./Controller"));
|
|
25
|
+
var _AdminController = _interopRequireDefault(require("./AdminController"));
|
|
26
|
+
var _middleware = require("./middleware");
|
|
27
|
+
Object.keys(_middleware).forEach(function (key) {
|
|
28
|
+
if (key === "default" || key === "__esModule") return;
|
|
29
|
+
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
|
|
30
|
+
if (key in exports && exports[key] === _middleware[key]) return;
|
|
31
|
+
Object.defineProperty(exports, key, {
|
|
32
|
+
enumerable: true,
|
|
33
|
+
get: function get() {
|
|
34
|
+
return _middleware[key];
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
});
|
|
38
|
+
var _constant = require("./constant");
|
|
39
|
+
Object.keys(_constant).forEach(function (key) {
|
|
40
|
+
if (key === "default" || key === "__esModule") return;
|
|
41
|
+
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
|
|
42
|
+
if (key in exports && exports[key] === _constant[key]) return;
|
|
43
|
+
Object.defineProperty(exports, key, {
|
|
44
|
+
enumerable: true,
|
|
45
|
+
get: function get() {
|
|
46
|
+
return _constant[key];
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
});
|
|
50
|
+
var _validate = require("./validate");
|
|
51
|
+
Object.keys(_validate).forEach(function (key) {
|
|
52
|
+
if (key === "default" || key === "__esModule") return;
|
|
53
|
+
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
|
|
54
|
+
if (key in exports && exports[key] === _validate[key]) return;
|
|
55
|
+
Object.defineProperty(exports, key, {
|
|
56
|
+
enumerable: true,
|
|
57
|
+
get: function get() {
|
|
58
|
+
return _validate[key];
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
|
|
63
|
+
var _default = _Server["default"];
|
|
64
|
+
exports["default"] = _default;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports["default"] = _default;
|
|
7
|
+
var _constant = require("../constant");
|
|
8
|
+
var _roleMiddleware = _interopRequireDefault(require("./roleMiddleware"));
|
|
9
|
+
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
|
|
10
|
+
function _default() {
|
|
11
|
+
var roles = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
|
|
12
|
+
return (0, _roleMiddleware["default"])(roles, _constant.USER_LEVEL.ADMIN);
|
|
13
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
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"] = _default;
|
|
8
|
+
var _jsonwebtoken = _interopRequireDefault(require("jsonwebtoken"));
|
|
9
|
+
var _error = require("@azteam/error");
|
|
10
|
+
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
|
|
11
|
+
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; }
|
|
12
|
+
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); } }
|
|
13
|
+
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); }); }; }
|
|
14
|
+
function systemLogin() {
|
|
15
|
+
var userData = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
|
|
16
|
+
var user = {};
|
|
17
|
+
if (userData) {
|
|
18
|
+
try {
|
|
19
|
+
user = JSON.parse(userData);
|
|
20
|
+
} catch (err) {}
|
|
21
|
+
}
|
|
22
|
+
return user;
|
|
23
|
+
}
|
|
24
|
+
function _default(cbLoginAPI) {
|
|
25
|
+
return /*#__PURE__*/function () {
|
|
26
|
+
var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req, res, next) {
|
|
27
|
+
var headers, token, data;
|
|
28
|
+
return _regeneratorRuntime().wrap(function _callee$(_context) {
|
|
29
|
+
while (1) {
|
|
30
|
+
switch (_context.prev = _context.next) {
|
|
31
|
+
case 0:
|
|
32
|
+
headers = req.headers;
|
|
33
|
+
if (!(headers['x-app-secret'] === process.env.SECRET_KEY)) {
|
|
34
|
+
_context.next = 5;
|
|
35
|
+
break;
|
|
36
|
+
}
|
|
37
|
+
req.user = systemLogin(headers['x-app-user']);
|
|
38
|
+
_context.next = 30;
|
|
39
|
+
break;
|
|
40
|
+
case 5:
|
|
41
|
+
token = null;
|
|
42
|
+
if (headers.authorization) {
|
|
43
|
+
token = headers.authorization;
|
|
44
|
+
}
|
|
45
|
+
if (!token) {
|
|
46
|
+
_context.next = 30;
|
|
47
|
+
break;
|
|
48
|
+
}
|
|
49
|
+
if (!token.startsWith('Bearer ')) {
|
|
50
|
+
_context.next = 22;
|
|
51
|
+
break;
|
|
52
|
+
}
|
|
53
|
+
token = token.replace('Bearer ', '');
|
|
54
|
+
_context.prev = 10;
|
|
55
|
+
req.user = _jsonwebtoken["default"].verify(token, process.env.SECRET_KEY);
|
|
56
|
+
return _context.abrupt("return", next());
|
|
57
|
+
case 15:
|
|
58
|
+
_context.prev = 15;
|
|
59
|
+
_context.t0 = _context["catch"](10);
|
|
60
|
+
if (!(_context.t0.name === 'TokenExpiredError')) {
|
|
61
|
+
_context.next = 19;
|
|
62
|
+
break;
|
|
63
|
+
}
|
|
64
|
+
throw new _error.ErrorException(_error.TOKEN_EXPIRED, _context.t0);
|
|
65
|
+
case 19:
|
|
66
|
+
throw new _error.ErrorException(_error.TOKEN_FAILED, _context.t0);
|
|
67
|
+
case 20:
|
|
68
|
+
_context.next = 30;
|
|
69
|
+
break;
|
|
70
|
+
case 22:
|
|
71
|
+
_context.next = 24;
|
|
72
|
+
return cbLoginAPI(token);
|
|
73
|
+
case 24:
|
|
74
|
+
data = _context.sent;
|
|
75
|
+
if (!data) {
|
|
76
|
+
_context.next = 29;
|
|
77
|
+
break;
|
|
78
|
+
}
|
|
79
|
+
req.user = data;
|
|
80
|
+
_context.next = 30;
|
|
81
|
+
break;
|
|
82
|
+
case 29:
|
|
83
|
+
return _context.abrupt("return", next((0, _error.ErrorException)(_error.TOKEN_FAILED)));
|
|
84
|
+
case 30:
|
|
85
|
+
return _context.abrupt("return", next());
|
|
86
|
+
case 31:
|
|
87
|
+
case "end":
|
|
88
|
+
return _context.stop();
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}, _callee, null, [[10, 15]]);
|
|
92
|
+
}));
|
|
93
|
+
return function (_x, _x2, _x3) {
|
|
94
|
+
return _ref.apply(this, arguments);
|
|
95
|
+
};
|
|
96
|
+
}();
|
|
97
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
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"] = _default;
|
|
8
|
+
var _lodash = _interopRequireDefault(require("lodash"));
|
|
9
|
+
var _querystring = _interopRequireDefault(require("querystring"));
|
|
10
|
+
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
|
|
11
|
+
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; }
|
|
12
|
+
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); } }
|
|
13
|
+
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); }); }; }
|
|
14
|
+
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; }
|
|
15
|
+
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; }
|
|
16
|
+
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; }
|
|
17
|
+
function _default(key) {
|
|
18
|
+
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
|
19
|
+
options = _objectSpread({
|
|
20
|
+
ttl: 300,
|
|
21
|
+
limitPage: 5
|
|
22
|
+
}, options);
|
|
23
|
+
return /*#__PURE__*/function () {
|
|
24
|
+
var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req, res, next) {
|
|
25
|
+
var redis, cacheKey, cacheData;
|
|
26
|
+
return _regeneratorRuntime().wrap(function _callee$(_context) {
|
|
27
|
+
while (1) {
|
|
28
|
+
switch (_context.prev = _context.next) {
|
|
29
|
+
case 0:
|
|
30
|
+
redis = req.redis;
|
|
31
|
+
if (!redis) {
|
|
32
|
+
_context.next = 16;
|
|
33
|
+
break;
|
|
34
|
+
}
|
|
35
|
+
cacheKey = key;
|
|
36
|
+
if (options.query) {
|
|
37
|
+
cacheKey = "".concat(cacheKey, ":").concat(_lodash["default"].get(req, options.query));
|
|
38
|
+
}
|
|
39
|
+
if (!req.paginate) {
|
|
40
|
+
_context.next = 10;
|
|
41
|
+
break;
|
|
42
|
+
}
|
|
43
|
+
if (!(_lodash["default"].isEmpty(req.query) && req.paginate.page <= options.limitPage)) {
|
|
44
|
+
_context.next = 9;
|
|
45
|
+
break;
|
|
46
|
+
}
|
|
47
|
+
cacheKey = "".concat(cacheKey, ":").concat(_querystring["default"].stringify(req.paginate));
|
|
48
|
+
_context.next = 10;
|
|
49
|
+
break;
|
|
50
|
+
case 9:
|
|
51
|
+
return _context.abrupt("return", next());
|
|
52
|
+
case 10:
|
|
53
|
+
_context.next = 12;
|
|
54
|
+
return redis.get(cacheKey);
|
|
55
|
+
case 12:
|
|
56
|
+
cacheData = _context.sent;
|
|
57
|
+
if (!cacheData) {
|
|
58
|
+
_context.next = 15;
|
|
59
|
+
break;
|
|
60
|
+
}
|
|
61
|
+
return _context.abrupt("return", res.json(cacheData));
|
|
62
|
+
case 15:
|
|
63
|
+
res.cache = {
|
|
64
|
+
key: cacheKey,
|
|
65
|
+
ttl: options.ttl
|
|
66
|
+
};
|
|
67
|
+
case 16:
|
|
68
|
+
return _context.abrupt("return", next());
|
|
69
|
+
case 17:
|
|
70
|
+
case "end":
|
|
71
|
+
return _context.stop();
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}, _callee);
|
|
75
|
+
}));
|
|
76
|
+
return function (_x, _x2, _x3) {
|
|
77
|
+
return _ref.apply(this, arguments);
|
|
78
|
+
};
|
|
79
|
+
}();
|
|
80
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
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"] = _default;
|
|
8
|
+
var _etag = _interopRequireDefault(require("etag"));
|
|
9
|
+
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
|
|
10
|
+
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; }
|
|
11
|
+
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); } }
|
|
12
|
+
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); }); }; }
|
|
13
|
+
function floorToMinute(time, minutes) {
|
|
14
|
+
var roundSecond = minutes * 60;
|
|
15
|
+
time = time - time % (Math.floor(time / roundSecond) * roundSecond);
|
|
16
|
+
return time;
|
|
17
|
+
}
|
|
18
|
+
function _default() {
|
|
19
|
+
var mTimeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 5;
|
|
20
|
+
return /*#__PURE__*/function () {
|
|
21
|
+
var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req, res, next) {
|
|
22
|
+
var etag_hash;
|
|
23
|
+
return _regeneratorRuntime().wrap(function _callee$(_context) {
|
|
24
|
+
while (1) {
|
|
25
|
+
switch (_context.prev = _context.next) {
|
|
26
|
+
case 0:
|
|
27
|
+
if (!(req.method === 'GET')) {
|
|
28
|
+
_context.next = 5;
|
|
29
|
+
break;
|
|
30
|
+
}
|
|
31
|
+
etag_hash = (0, _etag["default"])(req.url + floorToMinute(Math.floor(Date.now() / 1000), mTimeout));
|
|
32
|
+
if (!(req.headers['if-none-match'] === etag_hash)) {
|
|
33
|
+
_context.next = 4;
|
|
34
|
+
break;
|
|
35
|
+
}
|
|
36
|
+
return _context.abrupt("return", res.status(304).send());
|
|
37
|
+
case 4:
|
|
38
|
+
res.setHeader('ETag', etag_hash);
|
|
39
|
+
case 5:
|
|
40
|
+
return _context.abrupt("return", next());
|
|
41
|
+
case 6:
|
|
42
|
+
case "end":
|
|
43
|
+
return _context.stop();
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}, _callee);
|
|
47
|
+
}));
|
|
48
|
+
return function (_x, _x2, _x3) {
|
|
49
|
+
return _ref.apply(this, arguments);
|
|
50
|
+
};
|
|
51
|
+
}();
|
|
52
|
+
}
|