evaengine 0.11.2 → 1.0.1

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.
Files changed (141) hide show
  1. package/.ai/analysis.md +657 -0
  2. package/.ai/architecture/runtime.md +504 -0
  3. package/.ai/contracts/public-api.md +447 -0
  4. package/.ai/external-project-guide.md +248 -0
  5. package/.ai/vision.md +314 -0
  6. package/README.md +51 -62
  7. package/bin/engine +15 -21
  8. package/index.js +2 -18
  9. package/package.json +60 -64
  10. package/src/commands/index.js +12 -0
  11. package/{lib → src}/commands/interface.js +5 -11
  12. package/src/commands/make_entity.js +490 -0
  13. package/src/commands/tramp.js +34 -0
  14. package/{lib → src}/config/index.js +7 -9
  15. package/{lib → src}/di.js +11 -26
  16. package/src/engine.js +551 -0
  17. package/{lib → src}/entities/index.js +72 -82
  18. package/{lib → src}/exceptions/index.js +71 -92
  19. package/src/index.js +57 -0
  20. package/src/middlewares/auth.js +67 -0
  21. package/src/middlewares/auth_kong.js +28 -0
  22. package/src/middlewares/debug.js +88 -0
  23. package/src/middlewares/index.js +18 -0
  24. package/src/middlewares/providers.js +73 -0
  25. package/src/middlewares/session.js +58 -0
  26. package/{lib → src}/middlewares/trace.js +74 -86
  27. package/src/middlewares/validator.js +50 -0
  28. package/src/middlewares/view_cache.js +127 -0
  29. package/{lib → src}/services/cache.js +45 -56
  30. package/src/services/config.js +111 -0
  31. package/src/services/env.js +28 -0
  32. package/src/services/event_manager.js +84 -0
  33. package/src/services/http_client.js +160 -0
  34. package/src/services/index.js +27 -0
  35. package/src/services/interface.js +5 -0
  36. package/src/services/joi.js +13 -0
  37. package/src/services/jwt_token.js +89 -0
  38. package/src/services/jwt_token_kong.js +75 -0
  39. package/src/services/logger.js +148 -0
  40. package/src/services/namespace.js +176 -0
  41. package/src/services/now.js +49 -0
  42. package/src/services/providers.js +158 -0
  43. package/src/services/redis.js +55 -0
  44. package/src/services/rest_client.js +112 -0
  45. package/src/swagger/index.js +668 -0
  46. package/{lib → src}/utils/api_scaffold.js +26 -39
  47. package/src/utils/case_converter.js +33 -0
  48. package/src/utils/crc32.js +44 -0
  49. package/src/utils/datetime.js +13 -0
  50. package/src/utils/host.js +39 -0
  51. package/src/utils/index.js +35 -0
  52. package/{lib → src}/utils/pagination.js +22 -31
  53. package/src/utils/random.js +23 -0
  54. package/{lib → src}/utils/smart_query.js +27 -27
  55. package/src/utils/test.js +48 -0
  56. package/src/utils/wrapper.js +8 -0
  57. package/bin/engine-babel +0 -38
  58. package/lib/commands/index.js +0 -25
  59. package/lib/commands/index.js.map +0 -1
  60. package/lib/commands/interface.js.map +0 -1
  61. package/lib/commands/make_entity.js +0 -549
  62. package/lib/commands/make_entity.js.map +0 -1
  63. package/lib/commands/tramp.js +0 -53
  64. package/lib/commands/tramp.js.map +0 -1
  65. package/lib/config/index.js.map +0 -1
  66. package/lib/di.js.map +0 -1
  67. package/lib/engine.js +0 -558
  68. package/lib/engine.js.map +0 -1
  69. package/lib/entities/index.js.map +0 -1
  70. package/lib/exceptions/index.js.map +0 -1
  71. package/lib/index.js +0 -105
  72. package/lib/index.js.map +0 -1
  73. package/lib/middlewares/auth.js +0 -97
  74. package/lib/middlewares/auth.js.map +0 -1
  75. package/lib/middlewares/auth_kong.js +0 -48
  76. package/lib/middlewares/auth_kong.js.map +0 -1
  77. package/lib/middlewares/debug.js +0 -68
  78. package/lib/middlewares/debug.js.map +0 -1
  79. package/lib/middlewares/index.js +0 -45
  80. package/lib/middlewares/index.js.map +0 -1
  81. package/lib/middlewares/providers.js +0 -102
  82. package/lib/middlewares/providers.js.map +0 -1
  83. package/lib/middlewares/session.js +0 -76
  84. package/lib/middlewares/session.js.map +0 -1
  85. package/lib/middlewares/trace.js.map +0 -1
  86. package/lib/middlewares/validator.js +0 -71
  87. package/lib/middlewares/validator.js.map +0 -1
  88. package/lib/middlewares/view_cache.js +0 -160
  89. package/lib/middlewares/view_cache.js.map +0 -1
  90. package/lib/services/cache.js.map +0 -1
  91. package/lib/services/config.js +0 -140
  92. package/lib/services/config.js.map +0 -1
  93. package/lib/services/env.js +0 -40
  94. package/lib/services/env.js.map +0 -1
  95. package/lib/services/event_manager.js +0 -110
  96. package/lib/services/event_manager.js.map +0 -1
  97. package/lib/services/http_client.js +0 -178
  98. package/lib/services/http_client.js.map +0 -1
  99. package/lib/services/index.js +0 -70
  100. package/lib/services/index.js.map +0 -1
  101. package/lib/services/interface.js +0 -12
  102. package/lib/services/interface.js.map +0 -1
  103. package/lib/services/joi.js +0 -28
  104. package/lib/services/joi.js.map +0 -1
  105. package/lib/services/jwt_token.js +0 -120
  106. package/lib/services/jwt_token.js.map +0 -1
  107. package/lib/services/jwt_token_kong.js +0 -111
  108. package/lib/services/jwt_token_kong.js.map +0 -1
  109. package/lib/services/logger.js +0 -172
  110. package/lib/services/logger.js.map +0 -1
  111. package/lib/services/namespace.js +0 -188
  112. package/lib/services/namespace.js.map +0 -1
  113. package/lib/services/now.js +0 -69
  114. package/lib/services/now.js.map +0 -1
  115. package/lib/services/providers.js +0 -195
  116. package/lib/services/providers.js.map +0 -1
  117. package/lib/services/redis.js +0 -77
  118. package/lib/services/redis.js.map +0 -1
  119. package/lib/services/rest_client.js +0 -136
  120. package/lib/services/rest_client.js.map +0 -1
  121. package/lib/swagger/index.js +0 -684
  122. package/lib/swagger/index.js.map +0 -1
  123. package/lib/utils/api_scaffold.js.map +0 -1
  124. package/lib/utils/case_converter.js +0 -48
  125. package/lib/utils/case_converter.js.map +0 -1
  126. package/lib/utils/crc32.js +0 -22
  127. package/lib/utils/crc32.js.map +0 -1
  128. package/lib/utils/datetime.js +0 -21
  129. package/lib/utils/datetime.js.map +0 -1
  130. package/lib/utils/host.js +0 -48
  131. package/lib/utils/host.js.map +0 -1
  132. package/lib/utils/index.js +0 -61
  133. package/lib/utils/index.js.map +0 -1
  134. package/lib/utils/pagination.js.map +0 -1
  135. package/lib/utils/random.js +0 -33
  136. package/lib/utils/random.js.map +0 -1
  137. package/lib/utils/smart_query.js.map +0 -1
  138. package/lib/utils/test.js +0 -62
  139. package/lib/utils/test.js.map +0 -1
  140. package/lib/utils/wrapper.js +0 -9
  141. package/lib/utils/wrapper.js.map +0 -1
@@ -1,65 +1,41 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = undefined;
7
-
8
- var _fs = require('fs');
9
-
10
- var _fs2 = _interopRequireDefault(_fs);
11
-
12
- var _path = require('path');
13
-
14
- var _path2 = _interopRequireDefault(_path);
15
-
16
- var _assert = require('assert');
17
-
18
- var _assert2 = _interopRequireDefault(_assert);
19
-
20
- var _cloneDeep = require('lodash/cloneDeep');
21
-
22
- var _cloneDeep2 = _interopRequireDefault(_cloneDeep);
23
-
24
- var _sequelize = require('sequelize');
25
-
26
- var _sequelize2 = _interopRequireDefault(_sequelize);
27
-
28
- var _util = require('util');
29
-
30
- var _util2 = _interopRequireDefault(_util);
31
-
32
- var _di = require('../di');
33
-
34
- var _di2 = _interopRequireDefault(_di);
35
-
36
- var _utils = require('../utils');
37
-
38
- var _exceptions = require('../exceptions');
39
-
40
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import assert from 'assert';
4
+ import cloneDeep from 'lodash/cloneDeep.js';
5
+ import Sequelize from 'sequelize';
6
+ import { createRequire } from 'module';
7
+ import DI from '../di.js';
8
+ import { getMicroTimestamp } from '../utils/index.js';
9
+ import { StandardException } from '../exceptions/index.js';
10
+
11
+ const require = createRequire(import.meta.url);
41
12
 
42
13
  //From https://github.com/angelxmoreno/sequelize-isunique-validator
43
- _sequelize2.default.prototype.validateIsUnique = (col, msg) => {
14
+ Sequelize.prototype.validateIsUnique = (col, msg) => {
44
15
  const conditions = { where: {} };
45
16
  const message = msg || `${col} must be unique`;
46
17
  return function v(value, next) {
47
18
  const self = this;
48
- this.Model.describe().then(schema => {
19
+ this.Model.describe().then((schema) => {
49
20
  conditions.where[col] = value;
50
- Object.keys(schema).filter(field => schema[field].primaryKey).forEach(pk => {
51
- conditions.where[pk] = { $ne: self[pk] };
52
- });
53
- }).then(() => self.Model.count(conditions).then(found => {
54
- if (found !== 0) {
55
- return next(message);
56
- }
57
- return next();
58
- })).catch(next);
21
+ Object
22
+ .keys(schema)
23
+ .filter(field => schema[field].primaryKey)
24
+ .forEach((pk) => {
25
+ conditions.where[pk] = { $ne: self[pk] };
26
+ });
27
+ }).then(() =>
28
+ self.Model.count(conditions).then((found) => {
29
+ if (found !== 0) {
30
+ return next(message);
31
+ }
32
+ return next();
33
+ })).catch(next);
59
34
  };
60
35
  };
61
36
 
62
- let Entities = class Entities {
37
+
38
+ export default class Entities {
63
39
  /**
64
40
  * @param {string} entitiesPath
65
41
  * @param {Sequelize|Function} sequelizeInstance
@@ -77,18 +53,18 @@ let Entities = class Entities {
77
53
  * @returns {*}
78
54
  */
79
55
  static addTracer(options = {}) {
80
- const logger = _di2.default.get('logger');
56
+ const logger = DI.get('logger');
81
57
  return Object.assign(options, {
82
58
  benchmark: true,
83
59
  logging: (...args) => {
84
- const tracer = _di2.default.get('namespace').get('tracer');
60
+ const tracer = DI.get('namespace').get('tracer');
85
61
  const [query, cost] = args;
86
62
  let pushed = false;
87
63
  if (tracer && cost > 0) {
88
64
  tracer.queries.push({
89
65
  query,
90
66
  cost: cost * 1000,
91
- finishedAt: (0, _utils.getMicroTimestamp)()
67
+ finishedAt: getMicroTimestamp()
92
68
  });
93
69
  pushed = true;
94
70
  }
@@ -104,21 +80,28 @@ let Entities = class Entities {
104
80
  * @returns {Entities}
105
81
  */
106
82
  scan(entitiesPath, withAssociate = true) {
107
- (0, _assert2.default)(this.sequelize && this.sequelize instanceof _sequelize2.default, 'Scan entities require a sequelize instance');
108
-
109
- _fs2.default.readdirSync(entitiesPath).filter(file => {
110
- const fileArray = file.split('.');
111
- return file.indexOf('.') !== 0 && ['js', 'es6'].indexOf(fileArray.pop()) !== -1 && fileArray[0] !== 'index';
112
- }).forEach(file => {
113
- const entity = this.sequelize.import(_path2.default.join(entitiesPath, file));
114
- this.entities[entity.name] = entity;
115
- });
83
+ assert(this.sequelize && this.sequelize instanceof Sequelize, 'Scan entities require a sequelize instance');
84
+
85
+ fs
86
+ .readdirSync(entitiesPath)
87
+ .filter((file) => {
88
+ const fileArray = file.split('.');
89
+ return (file.indexOf('.') !== 0) &&
90
+ (['js', 'es6', 'cjs'].indexOf(fileArray.pop()) !== -1) && (fileArray[0] !== 'index');
91
+ })
92
+ .forEach((file) => {
93
+ const entityModule = require(path.join(entitiesPath, file));
94
+ const entityFactory = entityModule.default || entityModule;
95
+ const entity = typeof entityFactory === 'function' ?
96
+ entityFactory(this.sequelize, Sequelize) : entityFactory;
97
+ this.entities[entity.name] = entity;
98
+ });
116
99
 
117
100
  if (!withAssociate) {
118
101
  return this;
119
102
  }
120
103
 
121
- Object.values(this.entities).forEach(entity => {
104
+ Object.values(this.entities).forEach((entity) => {
122
105
  if ('associate' in entity) {
123
106
  entity.associate(this.entities);
124
107
  }
@@ -136,22 +119,30 @@ let Entities = class Entities {
136
119
  return this.sequelize;
137
120
  }
138
121
 
139
- const logger = _di2.default.get('logger').getInstance();
122
+ const logger = DI.get('logger').getInstance();
140
123
  if (!this.sequelize) {
141
- const config = _di2.default.get('config').get();
142
- const ns = _di2.default.get('namespace');
124
+ const config = DI.get('config').get();
125
+ const ns = DI.get('namespace');
143
126
  if (ns.isEnabled()) {
144
127
  //Inject sequelize inner namespace, refer: http://docs.sequelizejs.com/en/latest/docs/transactions/
145
- _sequelize2.default.cls = ns.use().getContext();
128
+ const context = ns.use().getContext();
129
+ if (typeof Sequelize.useCLS === 'function') {
130
+ Sequelize.useCLS(context);
131
+ } else {
132
+ Sequelize.cls = context;
133
+ }
146
134
  }
147
135
 
148
- const dbConfig = (0, _cloneDeep2.default)(config.db);
136
+ const dbConfig = cloneDeep(config.db);
149
137
  if (process.env.SEQUELIZE_REPLICATION_CONFIG_KEY) {
150
138
  dbConfig.replication = dbConfig[process.env.SEQUELIZE_REPLICATION_CONFIG_KEY];
151
139
  }
152
- this.sequelize = new _sequelize2.default(config.db.database, null, null, Object.assign({}, config.sequelize, dbConfig, Entities.addTracer()));
140
+ this.sequelize = new Sequelize(
141
+ config.db.database, null, null,
142
+ Object.assign({}, config.sequelize, dbConfig, Entities.addTracer())
143
+ );
153
144
  } else {
154
- this.sequelize = _util2.default.isFunction(this.sequelize) ? this.sequelize() : this.sequelize;
145
+ this.sequelize = typeof this.sequelize === 'function' ? this.sequelize() : this.sequelize;
155
146
  }
156
147
 
157
148
  this.scan(this.entitiesPath, withAssociate);
@@ -191,11 +182,11 @@ let Entities = class Entities {
191
182
  }, options = {}) {
192
183
  const inputObj = Object.assign({}, input);
193
184
  const typeAllowed = ['number', 'string', 'boolean'];
194
- Object.entries(inputObj).forEach(p => {
185
+ Object.entries(inputObj).forEach((p) => {
195
186
  const valType = typeof p[1];
196
187
  //Allow null type here
197
188
  if (typeAllowed.indexOf(valType) === -1 && p[1] !== null) {
198
- throw new _exceptions.StandardException(`SQL inputObj ${p[0]}:${p[1]} with unsupported type ${valType}.`);
189
+ throw new StandardException(`SQL inputObj ${p[0]}:${p[1]} with unsupported type ${valType}.`);
199
190
  } else if (valType === 'boolean') {
200
191
  if (p[1] === true) {
201
192
  inputObj[p[0]] = 1;
@@ -207,7 +198,8 @@ let Entities = class Entities {
207
198
  const columns = Object.keys(inputObj);
208
199
  const columnString = ['`', columns.join('`, `'), '`'].join('');
209
200
  const valueString = Object.entries(inputObj).map(([key]) => `$${key} \`${key}\``).join(' , ');
210
- const uniqueString = typeof uniqueCondition === 'string' ? uniqueCondition : [`SELECT * FROM ${tableName} WHERE `, this.getInstance().dialect.QueryGenerator.getWhereConditions(uniqueCondition)].join('');
201
+ const uniqueString = typeof uniqueCondition === 'string' ? uniqueCondition :
202
+ [`SELECT * FROM ${tableName} WHERE `, this.getInstance().dialect.QueryGenerator.getWhereConditions(uniqueCondition)].join('');
211
203
  /*
212
204
  Original Example:
213
205
  entities.getInstance().query(`INSERT INTO ${tableName}
@@ -221,8 +213,8 @@ let Entities = class Entities {
221
213
  )`, { bind, transaction, type: entities.getSequelize().QueryTypes.INSERT });
222
214
  */
223
215
 
224
- const sql = `INSERT INTO ${tableName}
225
- (${columnString})
216
+ const sql = `INSERT INTO ${tableName}
217
+ (${columnString})
226
218
  (
227
219
  SELECT *
228
220
  FROM (SELECT ${valueString}) AS tmp
@@ -233,7 +225,7 @@ let Entities = class Entities {
233
225
  return this.getInstance().query(sql, Object.assign({
234
226
  bind: inputObj,
235
227
  transaction,
236
- type: _sequelize2.default.QueryTypes.INSERT
228
+ type: Sequelize.QueryTypes.INSERT
237
229
  }, options));
238
230
  }
239
231
 
@@ -251,7 +243,7 @@ let Entities = class Entities {
251
243
  * @returns {Sequelize}
252
244
  */
253
245
  getSequelize() {
254
- return _sequelize2.default;
246
+ return Sequelize;
255
247
  }
256
248
 
257
249
  /**
@@ -278,6 +270,4 @@ let Entities = class Entities {
278
270
  this.init();
279
271
  return this.entities;
280
272
  }
281
- };
282
- exports.default = Entities;
283
- //# sourceMappingURL=index.js.map
273
+ }
@@ -1,61 +1,17 @@
1
- 'use strict';
1
+ import * as appRoot from 'app-root-path';
2
+ import path from 'path';
3
+ import { format } from 'util';
4
+ import crc32 from '../utils/crc32.js';
2
5
 
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.DatabaseIOException = exports.RestServiceIOException = exports.HttpRequestIOException = exports.IOException = exports.RuntimeException = exports.ResourceConflictedException = exports.OperationUnsupportedException = exports.ResourceNotFoundException = exports.OperationNotPermittedException = exports.UnauthorizedException = exports.RestServiceLogicException = exports.HttpRequestLogicException = exports.ModelInvalidateException = exports.FormInvalidateException = exports.InvalidArgumentException = exports.LogicException = exports.StandardException = undefined;
7
-
8
- var _appRootPath = require('app-root-path');
9
-
10
- var _appRootPath2 = _interopRequireDefault(_appRootPath);
11
-
12
- var _path = require('path');
13
-
14
- var _path2 = _interopRequireDefault(_path);
15
-
16
- var _util = require('util');
17
-
18
- var _crc = require('../utils/crc32');
19
-
20
- var _crc2 = _interopRequireDefault(_crc);
21
-
22
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
23
-
24
- function _extendableBuiltin(cls) {
25
- function ExtendableBuiltin() {
26
- var instance = Reflect.construct(cls, Array.from(arguments));
27
- Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
28
- return instance;
29
- }
30
-
31
- ExtendableBuiltin.prototype = Object.create(cls.prototype, {
32
- constructor: {
33
- value: cls,
34
- enumerable: false,
35
- writable: true,
36
- configurable: true
37
- }
38
- });
39
-
40
- if (Object.setPrototypeOf) {
41
- Object.setPrototypeOf(ExtendableBuiltin, cls);
42
- } else {
43
- ExtendableBuiltin.__proto__ = cls;
44
- }
45
-
46
- return ExtendableBuiltin;
47
- }
48
6
 
49
7
  /**
50
8
  * Make Error be able to work with JSON.stringify()
51
9
  */
52
10
  if (!('toJSON' in Error.prototype)) {
53
- Object.defineProperty(Error.prototype, 'toJSON', { //eslint-disable-line
11
+ Object.defineProperty(Error.prototype, 'toJSON', {
54
12
  value: function () {
55
- //eslint-disable-line
56
13
  const alt = {};
57
14
  Object.getOwnPropertyNames(this).forEach(function (key) {
58
- //eslint-disable-line
59
15
  alt[key] = this[key];
60
16
  }, this);
61
17
  return alt;
@@ -65,9 +21,11 @@ if (!('toJSON' in Error.prototype)) {
65
21
  });
66
22
  }
67
23
 
68
- let i18nHandler = _util.format;
69
24
 
70
- let factory = () => {};
25
+ let i18nHandler = format;
26
+
27
+ let factory = () => {
28
+ };
71
29
 
72
30
  /**
73
31
  * Exception interface
@@ -78,7 +36,7 @@ let factory = () => {};
78
36
  * throw new Exception(new Exception());
79
37
  * throw (new Exception()).i18n('some %d', 123)
80
38
  */
81
- let StandardException = exports.StandardException = class StandardException extends _extendableBuiltin(Error) {
39
+ export class StandardException extends Error {
82
40
  /**
83
41
  * Generate string hash by crc32
84
42
  * @param {string} str
@@ -86,7 +44,7 @@ let StandardException = exports.StandardException = class StandardException exte
86
44
  * @returns {string}
87
45
  */
88
46
  static hash(str, padstr = '0000000000') {
89
- const crcstr = (0, _crc2.default)(str).toString();
47
+ const crcstr = crc32(str).toString();
90
48
  return padstr.substring(0, padstr.length - crcstr.length) + crcstr;
91
49
  }
92
50
 
@@ -96,9 +54,9 @@ let StandardException = exports.StandardException = class StandardException exte
96
54
  * @param {string} fileName
97
55
  * @returns {Number}
98
56
  */
99
- static generateCode(className, fileName = __filename) {
100
- const namespace = fileName.replace(_appRootPath2.default.path, '').split(_path2.default.sep).join('/');
101
- const group = fileName === __filename ? '11111' : (0, _crc2.default)(namespace).toString().substring(0, 5);
57
+ static generateCode(className, fileName = import.meta.filename) {
58
+ const namespace = fileName.replace(appRoot.path, '').split(path.sep).join('/');
59
+ const group = fileName === import.meta.filename ? '11111' : crc32(namespace).toString().substring(0, 5);
102
60
  return parseInt(`${group}000${StandardException.hash(className)}`, 10);
103
61
  }
104
62
 
@@ -182,7 +140,7 @@ let StandardException = exports.StandardException = class StandardException exte
182
140
  this.details = throwingError ? exceptionOrMsg : [];
183
141
  this.prevError = {};
184
142
  this.code = null;
185
- this.filename = __filename;
143
+ this.filename = import.meta.filename;
186
144
  this.translated = false;
187
145
  this.importance = 0;
188
146
  if (throwingError === true) {
@@ -191,7 +149,7 @@ let StandardException = exports.StandardException = class StandardException exte
191
149
  }
192
150
 
193
151
  i18n(...args) {
194
- this.message = (0, _util.format)(...args);
152
+ this.message = format(...args);
195
153
  this.humanMessage = i18nHandler(...args);
196
154
  if (this.message !== this.humanMessage) {
197
155
  this.translated = true;
@@ -285,19 +243,24 @@ let StandardException = exports.StandardException = class StandardException exte
285
243
  humanMessage: this.getHumanMessage(),
286
244
  filename: this.getFileName(),
287
245
  prevError: this.getPrevError(),
288
- errors: Array.isArray(this.getDetails()) ? this.getDetails() : [this.getDetails()],
246
+ errors: Array.isArray(this.getDetails()) ?
247
+ this.getDetails() : [this.getDetails()],
289
248
  stack: StandardException.stackBeautifier(this.stack),
290
249
  fullStack: this.stack.split('\n')
291
250
  };
292
251
  }
293
- };
294
- let LogicException = exports.LogicException = class LogicException extends StandardException {
252
+ }
253
+
254
+ export class LogicException extends StandardException {
295
255
  get statusCode() {
296
256
  return 400;
297
257
  }
298
- };
299
- let InvalidArgumentException = exports.InvalidArgumentException = class InvalidArgumentException extends LogicException {};
300
- let FormInvalidateException = exports.FormInvalidateException = class FormInvalidateException extends InvalidArgumentException {
258
+ }
259
+
260
+ export class InvalidArgumentException extends LogicException {
261
+ }
262
+
263
+ export class FormInvalidateException extends InvalidArgumentException {
301
264
  constructor(exceptionOrMsg) {
302
265
  super(exceptionOrMsg);
303
266
  if (this.throwingError && exceptionOrMsg.isJoi === true) {
@@ -308,16 +271,18 @@ let FormInvalidateException = exports.FormInvalidateException = class FormInvali
308
271
  this.translated = true;
309
272
  }
310
273
  }
311
- };
312
- let ModelInvalidateException = exports.ModelInvalidateException = class ModelInvalidateException extends InvalidArgumentException {
274
+ }
275
+
276
+ export class ModelInvalidateException extends InvalidArgumentException {
313
277
  constructor(exceptionOrMsg) {
314
278
  super(exceptionOrMsg);
315
279
  if (this.throwingError) {
316
280
  this.details = exceptionOrMsg.errors;
317
281
  }
318
282
  }
319
- };
320
- let HttpRequestLogicException = exports.HttpRequestLogicException = class HttpRequestLogicException extends InvalidArgumentException {
283
+ }
284
+
285
+ export class HttpRequestLogicException extends InvalidArgumentException {
321
286
  /**
322
287
  * Support request promise error
323
288
  * https://github.com/request/promise-core/blob/master/lib/errors.js
@@ -382,43 +347,54 @@ let HttpRequestLogicException = exports.HttpRequestLogicException = class HttpRe
382
347
  getBusinessCode() {
383
348
  return this.businessCode;
384
349
  }
385
- };
386
- let RestServiceLogicException = exports.RestServiceLogicException = class RestServiceLogicException extends HttpRequestLogicException {
350
+ }
351
+
352
+ export class RestServiceLogicException extends HttpRequestLogicException {
387
353
  constructor(exceptionOrMsg) {
388
354
  super(exceptionOrMsg);
389
355
  if (this.throwingError && this.response && this.response.body) {
390
356
  this.prevError = factory(this.response.body);
391
357
  }
392
358
  }
393
- };
394
- let UnauthorizedException = exports.UnauthorizedException = class UnauthorizedException extends LogicException {
359
+ }
360
+
361
+ export class UnauthorizedException extends LogicException {
395
362
  get statusCode() {
396
363
  return 401;
397
364
  }
398
- };
399
- let OperationNotPermittedException = exports.OperationNotPermittedException = class OperationNotPermittedException extends LogicException {
365
+ }
366
+
367
+ export class OperationNotPermittedException extends LogicException {
400
368
  get statusCode() {
401
369
  return 403;
402
370
  }
403
- };
404
- let ResourceNotFoundException = exports.ResourceNotFoundException = class ResourceNotFoundException extends LogicException {
371
+ }
372
+
373
+ export class ResourceNotFoundException extends LogicException {
405
374
  get statusCode() {
406
375
  return 404;
407
376
  }
408
- };
409
- let OperationUnsupportedException = exports.OperationUnsupportedException = class OperationUnsupportedException extends LogicException {
377
+ }
378
+
379
+ export class OperationUnsupportedException extends LogicException {
410
380
  get statusCode() {
411
381
  return 405;
412
382
  }
413
- };
414
- let ResourceConflictedException = exports.ResourceConflictedException = class ResourceConflictedException extends LogicException {
383
+ }
384
+
385
+ export class ResourceConflictedException extends LogicException {
415
386
  get statusCode() {
416
387
  return 409;
417
388
  }
418
- };
419
- let RuntimeException = exports.RuntimeException = class RuntimeException extends StandardException {};
420
- let IOException = exports.IOException = class IOException extends RuntimeException {};
421
- let HttpRequestIOException = exports.HttpRequestIOException = class HttpRequestIOException extends IOException {
389
+ }
390
+
391
+ export class RuntimeException extends StandardException {
392
+ }
393
+
394
+ export class IOException extends RuntimeException {
395
+ }
396
+
397
+ export class HttpRequestIOException extends IOException {
422
398
  constructor(exceptionOrMsg) {
423
399
  super(exceptionOrMsg);
424
400
  if (this.throwingError && ['StatusCodeError', 'RequestError', 'TransformError'].includes(exceptionOrMsg.name)) {
@@ -466,17 +442,19 @@ let HttpRequestIOException = exports.HttpRequestIOException = class HttpRequestI
466
442
  getBusinessCode() {
467
443
  return this.businessCode;
468
444
  }
469
- };
470
- let RestServiceIOException = exports.RestServiceIOException = class RestServiceIOException extends HttpRequestIOException {
445
+ }
446
+
447
+ export class RestServiceIOException extends HttpRequestIOException {
471
448
  constructor(exceptionOrMsg) {
472
449
  super(exceptionOrMsg);
473
450
  if (this.throwingError && this.response && this.response.body) {
474
451
  this.prevError = factory(this.response.body);
475
452
  }
476
453
  }
477
- };
478
- let DatabaseIOException = exports.DatabaseIOException = class DatabaseIOException extends IOException {};
454
+ }
479
455
 
456
+ export class DatabaseIOException extends IOException {
457
+ }
480
458
 
481
459
  const exceptions = {
482
460
  StandardException,
@@ -498,7 +476,7 @@ const exceptions = {
498
476
  DatabaseIOException
499
477
  };
500
478
 
501
- factory = json => {
479
+ factory = (json) => {
502
480
  const {
503
481
  code, name, statusCode, message, prevError, errors, fullStack = []
504
482
  } = json;
@@ -508,15 +486,16 @@ factory = json => {
508
486
 
509
487
  let e = null;
510
488
  if (Object.keys(exceptions).includes(name)) {
511
- e = new exceptions[name](); //eslint-disable-line
489
+ e = new exceptions[name];
512
490
  } else if (statusCode < 500) {
513
491
  e = new LogicException(message);
514
492
  } else {
515
493
  e = new RuntimeException(message);
516
494
  }
517
495
 
518
- e.setCode(code).setDetails(errors).setPrevError(prevError);
496
+ e.setCode(code)
497
+ .setDetails(errors)
498
+ .setPrevError(prevError);
519
499
  e.stack = fullStack.join('\n');
520
500
  return e;
521
501
  };
522
- //# sourceMappingURL=index.js.map
package/src/index.js ADDED
@@ -0,0 +1,57 @@
1
+ import constitute from 'constitute';
2
+ import * as mysql from 'mysql';
3
+ import sequelize from 'sequelize';
4
+ import Joi from 'joi';
5
+ import EvaEngine, * as engine from './engine.js';
6
+ import * as swagger from './swagger/index.js';
7
+ import * as exceptions from './exceptions/index.js';
8
+ import * as services from './services/index.js';
9
+ import * as middlewares from './middlewares/index.js';
10
+ import * as ServiceProviders from './services/providers.js';
11
+ import * as MiddlewareProviders from './middlewares/providers.js';
12
+ import * as utils from './utils/index.js';
13
+ import Command, * as commands from './commands/index.js';
14
+ import Entities from './entities/index.js';
15
+
16
+ const providers = {
17
+ services: ServiceProviders,
18
+ middlewares: MiddlewareProviders
19
+ };
20
+
21
+ const { wrapper } = utils;
22
+
23
+ const {
24
+ DI,
25
+ express
26
+ } = engine;
27
+
28
+ /**
29
+ * @typedef {Object} engineCore
30
+ */
31
+ const core = {
32
+ EvaEngine,
33
+ Command,
34
+ DI,
35
+ Entities,
36
+ engine,
37
+ express,
38
+ commands,
39
+ dependencies: {
40
+ Joi,
41
+ constitute,
42
+ sequelize,
43
+ mysql
44
+ },
45
+ exceptions,
46
+ middlewares,
47
+ sequelize,
48
+ Joi,
49
+ swagger,
50
+ services,
51
+ providers,
52
+ wrapper,
53
+ utils
54
+ };
55
+
56
+ export default core;
57
+ export { core };
@@ -0,0 +1,67 @@
1
+ import constitute from 'constitute';
2
+ import wrapper from '../utils/wrapper.js';
3
+ import { UnauthorizedException } from '../exceptions/index.js';
4
+ import Config from '../services/config.js';
5
+ import Now from '../services/now.js';
6
+ import JsonWebToken from '../services/jwt_token.js';
7
+
8
+ /**
9
+ * @param _config {Config}
10
+ * @param token {JsonWebToken}
11
+ * @returns {function()}
12
+ * @constructor
13
+ */
14
+ function AuthMiddleware(_config, token, now) {
15
+ const config = _config.get();
16
+ return () => wrapper(async (req, res, next) => {
17
+ const jwToken = req.header('X-Token') || req.query.api_key;
18
+ if (config.token.faker.enable === true && req.auth && req.auth.uid) {
19
+ res.set('X-Uid', req.auth.uid);
20
+ return next();
21
+ }
22
+ if (config.token.faker.enable === true && jwToken === config.token.faker.key) {
23
+ req.auth = {
24
+ type: 'fake',
25
+ uid: config.token.faker.uid,
26
+ token: config.token.faker.key
27
+ };
28
+ res.set('X-Uid', config.token.faker.uid);
29
+ return next();
30
+ }
31
+ if (jwToken) {
32
+ let parsedToken = {};
33
+ try {
34
+ parsedToken = await token.find(jwToken);
35
+ } catch {
36
+ throw new UnauthorizedException('Token not recognizable');
37
+ }
38
+ const { uid, expiredAt } = parsedToken;
39
+ if (!uid) {
40
+ throw new UnauthorizedException('User info not found in token');
41
+ }
42
+ if (typeof expiredAt !== 'number' || expiredAt <= now.getTimestamp()) {
43
+ throw new UnauthorizedException('Token expired');
44
+ }
45
+ req.auth = {
46
+ type: 'jwt',
47
+ uid,
48
+ token: jwToken
49
+ };
50
+ res.set('X-Uid', uid);
51
+ return next();
52
+ }
53
+
54
+ if (req.session && req.session.uid) {
55
+ req.auth = {
56
+ type: 'session',
57
+ uid: req.session.uid,
58
+ token: ''
59
+ };
60
+ res.set('X-Uid', req.session.uid);
61
+ return next();
62
+ }
63
+ throw new UnauthorizedException('No authority token found');
64
+ });
65
+ }
66
+ constitute.Dependencies(Config, JsonWebToken, Now)(AuthMiddleware);
67
+ export default AuthMiddleware;