UNPKG

17.3 kBJavaScriptView Raw
1"use strict";
2
3var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4Object.defineProperty(exports, "__esModule", {
5 value: true
6});
7exports["default"] = exports.Api = void 0;
8var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
9var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
10var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
11var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
12var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
13var _get3 = _interopRequireDefault(require("@babel/runtime/helpers/get"));
14var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
15var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
16var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
17var _env = require("@lskjs/env");
18var _err = _interopRequireDefault(require("@lskjs/err"));
19var _module = _interopRequireDefault(require("@lskjs/module"));
20var _get4 = _interopRequireDefault(require("lodash/get"));
21function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; }
22function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
23// import hash from 'object-hash';
24// import Cacheman from 'cacheman';
25// import pick from 'lodash/pick';
26// import isArray from 'lodash/isArray';
27// import set from 'lodash/set';
28// import forEach from 'lodash/forEach';
29// import tryJSONparse from '@lskjs/utils/tryJSONparse';
30// import autobind from '@lskjs/utils/autobind';
31// import mapValues from 'lodash/mapValues';
32// import map from 'lodash/map';
33// import some from 'lodash/some';
34// import getDocsTemplate from './getDocsTemplate';
35var Api = /*#__PURE__*/function (_Module) {
36 (0, _inherits2["default"])(Api, _Module);
37 var _super = _createSuper(Api);
38 function Api(parent) {
39 var _this2;
40 var _this;
41 (0, _classCallCheck2["default"])(this, Api);
42 for (var _len = arguments.length, propsArray = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
43 propsArray[_key - 1] = arguments[_key];
44 }
45 _this = _super.call.apply(_super, [this, parent].concat(propsArray));
46 _this.__api = true;
47 (_this2 = _this).setProps.apply(_this2, propsArray.concat([{
48 '__lifecycle.create': new Date(),
49 __parent: parent,
50 app: parent && parent.app,
51 config: parent && parent.config
52 }]));
53 // this.__parent = parent;
54 // this.app = parent && parent.app;
55 // this.__config = parent && parent.config;
56 return _this;
57 }
58 (0, _createClass2["default"])(Api, [{
59 key: "init",
60 value: function () {
61 var _init = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
62 var _get2;
63 var _len2,
64 propsArray,
65 _key2,
66 _args = arguments;
67 return _regenerator["default"].wrap(function _callee$(_context) {
68 while (1) switch (_context.prev = _context.next) {
69 case 0:
70 for (_len2 = _args.length, propsArray = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
71 propsArray[_key2] = _args[_key2];
72 }
73 _context.next = 3;
74 return (_get2 = (0, _get3["default"])((0, _getPrototypeOf2["default"])(Api.prototype), "init", this)).call.apply(_get2, [this].concat(propsArray));
75 case 3:
76 if (this.app) {
77 _context.next = 5;
78 break;
79 }
80 throw new _err["default"]("API_APP_MISSING', 'Please use new ".concat(this.name, "(this) instead new ").concat(this.name, "(this.app)"));
81 case 5:
82 if (this.__parent) {
83 _context.next = 7;
84 break;
85 }
86 throw new _err["default"]("API_PARENT_MISSING', 'Please use new ".concat(this.name, "(this) instead new ").concat(this.name, "(this.app)"));
87 case 7:
88 this.paths = [].concat((0, _toConsumableArray2["default"])(this.__parent.paths || []), [this.path]);
89 case 8:
90 case "end":
91 return _context.stop();
92 }
93 }, _callee, this);
94 }));
95 function init() {
96 return _init.apply(this, arguments);
97 }
98 return init;
99 }() // async isAuth(req) {
100 // if (req.__errJwt) return false;
101 // if (!get(req, 'user._id')) return false;
102 // return true;
103 // }
104 }, {
105 key: "checkAuth",
106 value: function () {
107 var _checkAuth = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(req) {
108 return _regenerator["default"].wrap(function _callee2$(_context2) {
109 while (1) switch (_context2.prev = _context2.next) {
110 case 0:
111 if (!req.__errJwt) {
112 _context2.next = 2;
113 break;
114 }
115 throw req.__errJwt;
116 case 2:
117 if ((0, _get4["default"])(req, 'user._id')) {
118 _context2.next = 4;
119 break;
120 }
121 throw new _err["default"]('auth.unauthorized', {
122 status: 401
123 });
124 case 4:
125 case "end":
126 return _context2.stop();
127 }
128 }, _callee2);
129 }));
130 function checkAuth(_x) {
131 return _checkAuth.apply(this, arguments);
132 }
133 return checkAuth;
134 }() // async isAdmin(req) {
135 // if (req.__errJwt) return false;
136 // if (!get(req, 'user._id')) return false;
137 // if (!get(req, 'user.role') !== 'admin') return false;
138 // return true;
139 // }
140 }, {
141 key: "checkAdmin",
142 value: function () {
143 var _checkAdmin = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(req) {
144 var props,
145 _args3 = arguments;
146 return _regenerator["default"].wrap(function _callee3$(_context3) {
147 while (1) switch (_context3.prev = _context3.next) {
148 case 0:
149 props = _args3.length > 1 && _args3[1] !== undefined ? _args3[1] : {};
150 if (!(props.dev && _env.isDev)) {
151 _context3.next = 3;
152 break;
153 }
154 return _context3.abrupt("return");
155 case 3:
156 if (!req.__errJwt) {
157 _context3.next = 5;
158 break;
159 }
160 throw req.__errJwt;
161 case 5:
162 if (!((0, _get4["default"])(req, 'user.role') !== 'admin')) {
163 _context3.next = 7;
164 break;
165 }
166 throw new _err["default"]('auth.notadmin', {
167 status: 403
168 });
169 case 7:
170 case "end":
171 return _context3.stop();
172 }
173 }, _callee3);
174 }));
175 function checkAdmin(_x2) {
176 return _checkAdmin.apply(this, arguments);
177 }
178 return checkAdmin;
179 }()
180 }, {
181 key: "url",
182 value: function url(path, params) {
183 return this.app.url((this.path || '/api') + path, params);
184 }
185 }, {
186 key: "useMiddleware",
187 value: function () {
188 var _useMiddleware = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(middleware, req, res) {
189 return _regenerator["default"].wrap(function _callee5$(_context5) {
190 while (1) switch (_context5.prev = _context5.next) {
191 case 0:
192 return _context5.abrupt("return", new Promise(function (resolve, reject) {
193 return middleware(req, res, /*#__PURE__*/function () {
194 var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(err) {
195 return _regenerator["default"].wrap(function _callee4$(_context4) {
196 while (1) switch (_context4.prev = _context4.next) {
197 case 0:
198 if (!err) {
199 _context4.next = 2;
200 break;
201 }
202 return _context4.abrupt("return", reject(err));
203 case 2:
204 return _context4.abrupt("return", resolve());
205 case 3:
206 case "end":
207 return _context4.stop();
208 }
209 }, _callee4);
210 }));
211 return function (_x6) {
212 return _ref.apply(this, arguments);
213 };
214 }());
215 }));
216 case 1:
217 case "end":
218 return _context5.stop();
219 }
220 }, _callee5);
221 }));
222 function useMiddleware(_x3, _x4, _x5) {
223 return _useMiddleware.apply(this, arguments);
224 }
225 return useMiddleware;
226 }()
227 }, {
228 key: "__getRoutes",
229 value: function () {
230 var _getRoutes = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6() {
231 return _regenerator["default"].wrap(function _callee6$(_context6) {
232 while (1) switch (_context6.prev = _context6.next) {
233 case 0:
234 if (this.__lifecycle.runStart) {
235 _context6.next = 3;
236 break;
237 }
238 _context6.next = 3;
239 return this.__run();
240 case 3:
241 return _context6.abrupt("return", this.getRoutes());
242 case 4:
243 case "end":
244 return _context6.stop();
245 }
246 }, _callee6, this);
247 }));
248 function __getRoutes() {
249 return _getRoutes.apply(this, arguments);
250 }
251 return __getRoutes;
252 }()
253 }, {
254 key: "getRoutes",
255 value: function getRoutes() {
256 return {
257 '/': this.index.bind(this)
258 };
259 }
260 }, {
261 key: "index",
262 value: function () {
263 var _index = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7() {
264 return _regenerator["default"].wrap(function _callee7$(_context7) {
265 while (1) switch (_context7.prev = _context7.next) {
266 case 0:
267 return _context7.abrupt("return", "".concat(this.name, " \u2013 ok"));
268 case 1:
269 case "end":
270 return _context7.stop();
271 }
272 }, _callee7, this);
273 }));
274 function index() {
275 return _index.apply(this, arguments);
276 }
277 return index;
278 }()
279 }, {
280 key: "e404",
281 value: function e404(req) {
282 throw new _err["default"]('E_404', {
283 status: 404,
284 message: "Not found path ".concat(req.path),
285 path: req.path,
286 level: 'warn'
287 });
288 }
289
290 // cacheStore = new Cacheman('api', {
291 // ttl: 60,
292 // });
293 // e(...args) {
294 // return new Err(...args);
295 // }
296
297 // async validateParams(data, fields) {
298 // const errors = map(fields, (validator, param) => {
299 // if (validator && validator.required && data[param] == null) {
300 // return {
301 // name: 'api.validateParams.required',
302 // param,
303 // };
304 // }
305 // return undefined;
306 // }).filter(Boolean);
307
308 // if (some(errors, Boolean)) {
309 // throw new Err({
310 // code: 'api.validateParams',
311 // status: 400,
312 // data: {
313 // errors,
314 // },
315 // });
316 // }
317
318 // return mapValues(fields, (validator, param) => {
319 // const aliases = [param, ...(validator.alias || [])];
320 // // eslint-disable-next-line no-restricted-syntax
321 // for (const param2 of aliases) {
322 // if (data[param2] != null) return data[param2];
323 // }
324 // return null;
325 // });
326 // }
327
328 // getListParams(req) {
329 // const { data } = req;
330 // const params = mapValues(pick(data, ['filter', 'sort', 'skip', 'limit', 'select', 'view', 'operation']), (a) =>
331 // tryJSONparse(a),
332 // );
333
334 // if (!params.filter) params.filter = {};
335 // if (req.data) {
336 // forEach(req.data, (val, key) => {
337 // if (key.substr(0, 'filter.'.length) === 'filter.') {
338 // set(params, key, val);
339 // }
340 // if (key.substr(0, 'sort.'.length) === 'sort.') {
341 // set(params, key, val);
342 // }
343 // });
344 // }
345 // if (params.limit > 100) params.limit = 100;
346 // if (!params.select) params.select = [];
347 // if (typeof params.select === 'string') {
348 // params.select = params.select
349 // .trim()
350 // .split(',')
351 // .map((a) => a.trim());
352 // }
353 // if (!isArray(params.select)) throw new Err('select not array');
354 // if (!params.view) params.view = 'default';
355 // // params.operation = req.data.operation;
356
357 // return params;
358 // }
359
360 // getGteLte(item) {
361 // const $gte = get(item, '[0]');
362 // const $lte = get(item, '[1]');
363 // const res = {};
364 // if ($lte !== null && typeof $lte !== 'undefined') {
365 // res.$lte = $lte;
366 // }
367 // if ($gte !== null && typeof $gte !== 'undefined') {
368 // res.$gte = $gte;
369 // }
370 // if (!Object.keys(res).length) return null;
371 // return res;
372 // }
373 // assign(model, params, fields = []) {
374 // if (fields.length === 0) {
375 // console.error('Api.assign empty fields'); // eslint-disable-line no-console
376 // return;
377 // }
378 // fields.forEach((field) => {
379 // if (params[field] === undefined) return;
380 // model[field] = params[field]; // eslint-disable-line no-param-reassign
381 // if (!model.markModified) return;
382 // model.markModified(field);
383 // });
384 // }
385 // isAdmin(req) {
386 // if (req.user?.role !== 'admin') throw this.e(403, '!admin');
387 // // return req.user?.role === 'admin';
388 // }
389 // equal(objectId1, objectId2) {
390 // return String(objectId1) === String(objectId2);
391 // }
392 // findAndCountByParams(Model, params, params2) {
393 // const { then = (a) => a } = params2; // = a => a
394 // return Promise.props({
395 // __pack: 1,
396 // count: params.count || params.count === '' ? Model.countByParams(params) : undefined,
397 // data: Model.prepare(then(Model.findByParams(params, params2)), params2),
398 // });
399 // }
400 // withSearchParams(data, field) {
401 // const { search, filter = {}, ...other } = data;
402 // if (!search) return data;
403 // return {
404 // ...other,
405 // filter: {
406 // ...filter,
407 // $and: [
408 // {
409 // [field]: {
410 // $regex: search,
411 // $options: 'i',
412 // },
413 // },
414 // ],
415 // },
416 // };
417 // }
418 // enableCache = false;
419 // async cache(key, ...args) {
420 // const [fn, params = { ttl: 60 }] = args.reverse();
421 // if (!this.enableCache) return fn();
422 // const { ttl } = params;
423 // let hashedKey;
424 // try {
425 // hashedKey = hash(key);
426 // } catch (err) {
427 // try {
428 // hashedKey = hash(JSON.stringify(key));
429 // } catch (err2) {
430 // console.error('Api.cache', err2); //eslint-disable-line
431 // hashedKey = '!!!ERR!!!';
432 // }
433 // }
434 // const value = await this.cacheStore.get(hashedKey);
435 // if (value) return value;
436 // const res = await fn();
437 // this.cacheStore.set(hashedKey, res, ttl);
438 // return res;
439 // }
440
441 // getDocsRoutes({ path, ...props } = {}) {
442 // const params = {
443 // name: get(this, 'app.config.about.title'),
444 // description: get(this, 'app.config.about.description'),
445 // docs: path ? this.app.url(`${path}/docs`) : this.url('/docs'),
446 // docsJson: path ? this.app.url(`${path}/docs.json`) : this.url('/docs.json'),
447 // path,
448 // ...props,
449 // };
450 // return {
451 // '': () => params,
452 // '/docs': (req, res) => res.send(getDocsTemplate(params)),
453 // '/docs.json': (req, res) => res.json(this.getDocs(this, params)),
454 // };
455 // }
456 }]);
457 return Api;
458}(_module["default"]);
459exports.Api = Api;
460var _default = Api;
461exports["default"] = _default;
462//# sourceMappingURL=Api.js.map
\No newline at end of file