evaengine 1.0.0 → 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 (47) hide show
  1. package/package.json +1 -1
  2. package/src/commands/index.js +12 -0
  3. package/src/commands/interface.js +45 -0
  4. package/src/commands/make_entity.js +490 -0
  5. package/src/commands/tramp.js +34 -0
  6. package/src/config/index.js +96 -0
  7. package/src/di.js +84 -0
  8. package/src/engine.js +551 -0
  9. package/src/entities/index.js +273 -0
  10. package/src/exceptions/index.js +501 -0
  11. package/src/middlewares/auth.js +67 -0
  12. package/src/middlewares/auth_kong.js +28 -0
  13. package/src/middlewares/debug.js +88 -0
  14. package/src/middlewares/index.js +18 -0
  15. package/src/middlewares/providers.js +73 -0
  16. package/src/middlewares/session.js +58 -0
  17. package/src/middlewares/trace.js +229 -0
  18. package/src/middlewares/validator.js +50 -0
  19. package/src/middlewares/view_cache.js +127 -0
  20. package/src/services/cache.js +223 -0
  21. package/src/services/config.js +111 -0
  22. package/src/services/env.js +28 -0
  23. package/src/services/event_manager.js +84 -0
  24. package/src/services/http_client.js +160 -0
  25. package/src/services/index.js +27 -0
  26. package/src/services/interface.js +5 -0
  27. package/src/services/joi.js +13 -0
  28. package/src/services/jwt_token.js +89 -0
  29. package/src/services/jwt_token_kong.js +75 -0
  30. package/src/services/logger.js +148 -0
  31. package/src/services/namespace.js +176 -0
  32. package/src/services/now.js +49 -0
  33. package/src/services/providers.js +158 -0
  34. package/src/services/redis.js +55 -0
  35. package/src/services/rest_client.js +112 -0
  36. package/src/swagger/index.js +668 -0
  37. package/src/utils/api_scaffold.js +240 -0
  38. package/src/utils/case_converter.js +33 -0
  39. package/src/utils/crc32.js +44 -0
  40. package/src/utils/datetime.js +13 -0
  41. package/src/utils/host.js +39 -0
  42. package/src/utils/index.js +35 -0
  43. package/src/utils/pagination.js +260 -0
  44. package/src/utils/random.js +23 -0
  45. package/src/utils/smart_query.js +342 -0
  46. package/src/utils/test.js +48 -0
  47. package/src/utils/wrapper.js +8 -0
@@ -0,0 +1,223 @@
1
+ import constitute from 'constitute';
2
+ import { OperationUnsupportedException } from './../exceptions/index.js';
3
+ import Redis from './redis.js';
4
+ import DI from './../di.js';
5
+ import Config from './config.js';
6
+ import ServiceInterface from './interface.js';
7
+
8
+ export class Store {
9
+ getInstance() {
10
+ return this;
11
+ }
12
+
13
+ has() {
14
+ return Promise.resolve(false);
15
+ }
16
+
17
+ get() {
18
+ return Promise.resolve(null);
19
+ }
20
+
21
+ set() {
22
+ return Promise.resolve(this);
23
+ }
24
+
25
+ del() {
26
+ return Promise.resolve(this);
27
+ }
28
+
29
+ flush() {
30
+ return Promise.resolve(true);
31
+ }
32
+
33
+ tags() {
34
+ throw new OperationUnsupportedException('Not support tag feature');
35
+ }
36
+ }
37
+
38
+ export class NullStore extends Store {
39
+ namespace() {
40
+ return this;
41
+ }
42
+
43
+ tags() {
44
+ return this;
45
+ }
46
+ }
47
+
48
+ export class RedisNamespaceStore extends Store {
49
+ constructor(prefix, namespace, redis) {
50
+ super();
51
+ this.prefix = prefix;
52
+ this.namespace = namespace;
53
+ this.redis = redis;
54
+ }
55
+
56
+ getInstance() {
57
+ return this.redis;
58
+ }
59
+
60
+ has(key) {
61
+ return this.redis.exists(this.key(key)).then(res => res > 0);
62
+ }
63
+
64
+ key(key) {
65
+ return this.prefix ? [this.prefix, this.namespace, key].join(':') : key;
66
+ }
67
+
68
+ get(key) {
69
+ return this.redis.get(this.key(key)).then(res => JSON.parse(res));
70
+ }
71
+
72
+ del(key) {
73
+ return this.redis.del(this.key(key));
74
+ }
75
+
76
+ set(key, value, minutes, mutex) {
77
+ const args = [
78
+ this.key(key),
79
+ JSON.stringify(value)
80
+ ];
81
+ if (minutes) {
82
+ args.push('ex', minutes * 60);
83
+ }
84
+ if (mutex) {
85
+ const m = mutex.toUpperCase();
86
+ if (m === 'NX' || m === 'XX') {
87
+ args.push(m);
88
+ }
89
+ }
90
+ return this.redis.set(...args);
91
+ }
92
+
93
+ flush() {
94
+ return this.redis.keys([this.prefix, this.namespace, '*'].join(':'))
95
+ .then((keys) => {
96
+ if (keys.length) {
97
+ return this.redis.del(keys);
98
+ }
99
+ return 0;
100
+ });
101
+ }
102
+ }
103
+
104
+ export class RedisStore extends Store {
105
+ constructor(prefix, redis) {
106
+ super();
107
+ this.prefix = prefix;
108
+ this.namespaceHandler = {};
109
+ this.redis = redis || DI.get('redis').getInstance();
110
+ }
111
+
112
+ getInstance() {
113
+ return this.redis;
114
+ }
115
+
116
+ namespace(namespace) {
117
+ if ({}.hasOwnProperty.call(this.namespaceHandler, namespace)) {
118
+ return this.namespaceHandler[namespace];
119
+ }
120
+ this.namespaceHandler[namespace] = new RedisNamespaceStore(this.prefix, namespace, this.redis);
121
+ return this.namespaceHandler[namespace];
122
+ }
123
+
124
+ has(key) {
125
+ return this.redis.exists(this.key(key));
126
+ }
127
+
128
+ key(key) {
129
+ return this.prefix ? [this.prefix, key].join(':') : key;
130
+ }
131
+
132
+ get(key) {
133
+ return this.redis.get(this.key(key)).then(res => JSON.parse(res));
134
+ }
135
+
136
+ del(key) {
137
+ return this.redis.del(this.key(key));
138
+ }
139
+
140
+ set(key, value, minutes, mutex) {
141
+ const args = [
142
+ this.key(key),
143
+ JSON.stringify(value)
144
+ ];
145
+ if (minutes) {
146
+ args.push('ex', minutes * 60);
147
+ }
148
+ if (mutex) {
149
+ const m = mutex.toUpperCase();
150
+ if (m === 'NX' || m === 'XX') {
151
+ args.push(m);
152
+ }
153
+ }
154
+ return this.redis.set(...args);
155
+ }
156
+
157
+ flush() {
158
+ return this.redis.flushall();
159
+ }
160
+ }
161
+
162
+ class Cache extends ServiceInterface {
163
+ constructor(config) {
164
+ super();
165
+ this.config = config.get('cache');
166
+ this.prefix = this.config.prefix || 'eva';
167
+ this.driver = this.config.driver;
168
+ this.store = null;
169
+ }
170
+
171
+ setStore(store) {
172
+ this.store = store;
173
+ return this;
174
+ }
175
+
176
+ /**
177
+ * @returns {Store}
178
+ */
179
+ getStore() {
180
+ if (this.store) {
181
+ return this.store;
182
+ }
183
+ this.store = this.driver === 'redis' ?
184
+ new RedisStore(this.prefix) : new NullStore(this.prefix);
185
+ return this.store;
186
+ }
187
+
188
+ setPrefix(prefix) {
189
+ this.prefix = prefix;
190
+ }
191
+
192
+ getPrefix() {
193
+ return this.prefix;
194
+ }
195
+
196
+ namespace(...args) {
197
+ return this.getStore().namespace(...args);
198
+ }
199
+
200
+ has(key) {
201
+ return this.getStore().has(key);
202
+ }
203
+
204
+ get(key) {
205
+ return this.getStore().get(key);
206
+ }
207
+
208
+ set(...args) {
209
+ return this.getStore().set(...args);
210
+ }
211
+
212
+ del(...args) {
213
+ return this.getStore().del(...args);
214
+ }
215
+
216
+ flush() {
217
+ return this.getStore().flush();
218
+ }
219
+ }
220
+
221
+ constitute.Dependencies(Config, Redis)(Cache);
222
+ export default Cache;
223
+
@@ -0,0 +1,111 @@
1
+ import _ from 'lodash';
2
+ import { createRequire } from 'module';
3
+ import constitute from 'constitute';
4
+ import * as springConfigClient from 'cloud-config-client';
5
+ import Env from './env.js';
6
+ import EngineConfig from '../config/index.js';
7
+ import ServiceInterface from './interface.js';
8
+
9
+ const require = createRequire(import.meta.url);
10
+
11
+ class Config extends ServiceInterface {
12
+ /**
13
+ * @param env {Env}
14
+ */
15
+ constructor(env) {
16
+ super();
17
+ this.env = env;
18
+ this.path = null;
19
+ this.mergedFiles = [];
20
+ this.config = null;
21
+ }
22
+
23
+ setPath(path) {
24
+ this.path = path;
25
+ return this;
26
+ }
27
+
28
+ /**
29
+ * Resolve configurations from Spring Cloud Config Server.
30
+ * @param endpoint
31
+ * @param name
32
+ * @param profiles
33
+ * @param label
34
+ * @returns {Promise.<void>}
35
+ */
36
+ async resolveSpringConfig({
37
+ endpoint,
38
+ name,
39
+ profiles,
40
+ label = 'master'
41
+ }) {
42
+ if (!this.config) {
43
+ this.config = this.loadConfigFromFiles();
44
+ }
45
+ const configRemote = await springConfigClient.load({
46
+ endpoint,
47
+ name,
48
+ profiles: _.isString(profiles) ? profiles.split(',') : [],
49
+ label
50
+ });
51
+ configRemote.forEach((key, value) => {
52
+ _.set(this.config, key, value);
53
+ });
54
+ }
55
+
56
+ get(key) {
57
+ if (this.config) {
58
+ return key ? Config.search(key, this.config) : this.config;
59
+ }
60
+ this.config = this.loadConfigFromFiles();
61
+ return key ? Config.search(key, this.config) : this.config;
62
+ }
63
+
64
+ loadConfigFromFiles() {
65
+ const env = this.env.get();
66
+ const configPath = this.path;
67
+ const pathDefault = `${configPath}/config.default.cjs`;
68
+ const pathEnv = `${configPath}/config.${env}.cjs`;
69
+ const pathLocal = `${configPath}/config.local.${env}.cjs`;
70
+
71
+
72
+ const configDefault = require(pathDefault);
73
+ this.mergedFiles.push(pathDefault);
74
+ const configEnv = require(pathEnv);
75
+ this.mergedFiles.push(pathEnv);
76
+ let configLocal = {};
77
+ try {
78
+ configLocal = require(pathLocal);
79
+ this.mergedFiles.push(pathLocal);
80
+ } catch {
81
+ configLocal = {};
82
+ }
83
+
84
+
85
+ return _.merge({}, EngineConfig, configDefault, configEnv, configLocal);
86
+ }
87
+
88
+ getMergedFiles() {
89
+ return this.mergedFiles;
90
+ }
91
+
92
+ reload() {
93
+ this.config = null;
94
+ }
95
+
96
+ /**
97
+ * @param {string} keyString
98
+ * @param {Object} target
99
+ * @returns {*}
100
+ */
101
+ static search(keyString, target) {
102
+ if (typeof keyString !== 'string') {
103
+ return target;
104
+ }
105
+ return _.get(target, keyString);
106
+ }
107
+ }
108
+
109
+ constitute.Dependencies(Env)(Config);
110
+ export default Config;
111
+
@@ -0,0 +1,28 @@
1
+ import ServiceInterface from './interface.js';
2
+
3
+ let env = null;
4
+ export const TYPES = {
5
+ PRODUCTION: 'production',
6
+ TEST: 'test',
7
+ DEVELOPMENT: 'development'
8
+ };
9
+
10
+ export default class Env extends ServiceInterface {
11
+ get() {
12
+ env = [TYPES.PRODUCTION, TYPES.TEST, TYPES.DEVELOPMENT].indexOf(process.env.NODE_ENV) > -1
13
+ ? process.env.NODE_ENV : TYPES.DEVELOPMENT;
14
+ return env;
15
+ }
16
+
17
+ isTest() {
18
+ return this.get() === TYPES.TEST;
19
+ }
20
+
21
+ isProduction() {
22
+ return this.get() === TYPES.PRODUCTION;
23
+ }
24
+
25
+ isDevelopment() {
26
+ return this.get() === TYPES.DEVELOPMENT;
27
+ }
28
+ }
@@ -0,0 +1,84 @@
1
+ import constitute from 'constitute';
2
+ import EventEmitter from 'events';
3
+ import camelCase from 'lodash/camelCase.js';
4
+ import { RuntimeException } from '../exceptions/index.js';
5
+ import Logger from './logger.js';
6
+ import ServiceInterface from './interface.js';
7
+
8
+ /**
9
+ * A strict version of EventEmitter
10
+ * 1. listener must be a standard class
11
+ * 2. unregistered event not allow to emit
12
+ * 3. all events register and trigger will be recorded
13
+ */
14
+ class EventManager extends ServiceInterface {
15
+ constructor(logger) {
16
+ super();
17
+ this.logger = logger;
18
+ this.emitter = new EventEmitter();
19
+ this.events = new Set();
20
+ }
21
+
22
+ getProto() {
23
+ return EventEmitter;
24
+ }
25
+
26
+ getAllowEvents() {
27
+ return this.events;
28
+ }
29
+
30
+ getEmitter() {
31
+ //TODO: 屏蔽写入
32
+ return this.emitter;
33
+ }
34
+
35
+ /**
36
+ * Allow to register a class such like
37
+ * class Foo { get prefix(){ return 'foo'} get actions() { return ['bar']} }
38
+ * @param ListenerClass
39
+ * @returns {EventManager}
40
+ */
41
+ addListener(ListenerClass) {
42
+ if (typeof ListenerClass !== 'function') {
43
+ throw new RuntimeException('Not a standard listener input');
44
+ }
45
+ const listener = new ListenerClass();
46
+ const { prefix, actions } = listener;
47
+ if (!prefix || !actions) {
48
+ throw new RuntimeException('Not a standard listener input');
49
+ }
50
+
51
+ const events = {};
52
+ const eventsCount = this.events.size;
53
+ for (const action of actions) {
54
+ events[[prefix, action, 'before'].join(':')] = camelCase(['before', action].join('_'));
55
+ events[[prefix, action, 'after'].join(':')] = camelCase(['after', action].join('_'));
56
+ }
57
+
58
+ //TODO: 用Set保存注册的事件
59
+ for (const [eventName, callback] of Object.entries(events)) {
60
+ this.events.add(eventName);
61
+ if (Reflect.has(listener, callback) === false) {
62
+ continue;
63
+ }
64
+ this.emitter.addListener(eventName, listener[callback]);
65
+ }
66
+
67
+ if (eventsCount + Object.keys(events).length !== this.events.size) {
68
+ throw new RuntimeException('Repeated event name has been registered, please check');
69
+ }
70
+
71
+ // this.logger.debug('Registered events', this.emitter.eventNames());
72
+ return this;
73
+ }
74
+
75
+ emit(eventName, callback) {
76
+ if (!this.events.has(eventName)) {
77
+ throw new RuntimeException(`Event ${eventName} not registered yet`);
78
+ }
79
+ return this.emitter.emit(eventName, callback);
80
+ }
81
+ }
82
+
83
+ constitute.Dependencies(Logger)(EventManager);
84
+ export default EventManager;
@@ -0,0 +1,160 @@
1
+ import constitute from 'constitute';
2
+ import request from 'request-promise-native';
3
+ import Config from './config.js';
4
+ import Logger from './logger.js';
5
+ import { HttpRequestLogicException, HttpRequestIOException } from '../exceptions/index.js';
6
+ import ServiceInterface from './interface.js';
7
+
8
+ export const deepClone = obj =>
9
+ JSON.parse(JSON.stringify(obj));
10
+
11
+ const TOO_LONG_BODY = '____TLDR____';
12
+
13
+ let debugFlag = false;
14
+ /* eslint-disable */
15
+ //Mod version of https://github.com/request/request-debug
16
+ export const requestDebug = (logger, maxBodyLength = process.env.MAX_REQUEST_DEBUG_BODY || 3000) => {
17
+ if (debugFlag === true) {
18
+ return;
19
+ }
20
+
21
+ let proto = {};
22
+ let debugId = 0;
23
+ if (request.Request) {
24
+ proto = request.Request.prototype;
25
+ } else if (request.get && request.post) {
26
+ // The object returned by request.defaults() doesn't include the
27
+ // Request property, so do this horrible thing to get at it. Per
28
+ // Wikipedia, port 4 is unassigned.
29
+ const req = request('http://localhost:4').on('error', () => {
30
+ });
31
+ proto = req.constructor.prototype;
32
+ } else {
33
+ throw new Error('Pass the object returned by require("request") to this function.');
34
+ }
35
+ if (proto._initBeforeDebug) {
36
+ return;
37
+ }
38
+
39
+ proto._initBeforeDebug = proto.init;
40
+
41
+ const ignoreDebug = (headers) => {
42
+ if (!headers || Object.keys(headers).length < 1) {
43
+ return {};
44
+ }
45
+ return Object.keys(headers)
46
+ .filter(key => !key.startsWith('x-debug'))
47
+ .reduce((res, key) => (res[key] = headers[key], res), {});
48
+ };
49
+
50
+ proto.init = function () {
51
+ if (this._debugId) {
52
+ return;
53
+ }
54
+ this.on('request', function (req) {
55
+ const data = {
56
+ headers: deepClone(this.headers)
57
+ };
58
+ if (this.body) {
59
+ data.body = maxBodyLength > 0 && this.body.toString().length < maxBodyLength ? this.body.toString('utf8') : TOO_LONG_BODY;
60
+ }
61
+
62
+ logger.verbose('[HTTP_REQUEST_%s] [%s %s] [REQ_HEADERS: %s] [REQ_BODY: %s]', this._debugId,
63
+ this.method.toUpperCase(), this.uri.href, JSON.stringify(data.headers), data.body || ''
64
+ );
65
+ }).on('response', function (res) {
66
+ if (this.callback) {
67
+ return;
68
+ }
69
+
70
+ const bodyLength = res.headers['content-length'] || (res.body ? res.body.toString().length : 0);
71
+ logger.verbose('[HTTP_RESPONSE_%s] [%s %s] [%s] [RES_HEADERS: %s] [RES_BODY: %s]', this._debugId,
72
+ this.method.toUpperCase(), this.uri.href, res.statusCode, JSON.stringify(ignoreDebug(res.headers)),
73
+ bodyLength > maxBodyLength ? TOO_LONG_BODY : res.body || ''
74
+ );
75
+ }).on('complete', function (res) {
76
+ if (!this.callback) {
77
+ return;
78
+ }
79
+
80
+ const bodyLength = res.headers['content-length'] || (res.body ? res.body.toString().length : 0);
81
+ logger.verbose('[HTTP_RESPONSE_%s] [%s %s] [%s] [RES_HEADERS: %s] [RES_BODY: %s]', this._debugId,
82
+ this.method.toUpperCase(), this.uri.href, res.statusCode, JSON.stringify(ignoreDebug(res.headers)),
83
+ bodyLength > maxBodyLength ? TOO_LONG_BODY : res.body || ''
84
+ );
85
+ }).on('redirect', function () {
86
+
87
+ logger.verbose('[HTTP_REDIRECT_%s] [%s %s] [%s] [RES_HEADERS: %s] [RES_BODY: %s]', this._debugId,
88
+ this.method.toUpperCase(), this.uri.href, this.response.statusCode, JSON.stringify(ignoreDebug(this.response.headers)), '');
89
+ });
90
+ this._debugId = ++debugId;
91
+ return proto._initBeforeDebug.apply(this, arguments);
92
+ };
93
+
94
+ debugFlag = true;
95
+ };
96
+ /* eslint-enable */
97
+
98
+ class HttpClient extends ServiceInterface {
99
+ /**
100
+ * @param config {Config}
101
+ * @param logger {Logger}
102
+ */
103
+ constructor(config, logger) {
104
+ super();
105
+ this.config = config.get();
106
+ this.client = request;
107
+ requestDebug(logger);
108
+ }
109
+
110
+ getProto() {
111
+ return request;
112
+ }
113
+
114
+ getInstance() {
115
+ return this.client;
116
+ }
117
+
118
+ async request(params) {
119
+ try {
120
+ return await this.client(params);
121
+ } catch (e) {
122
+ const { statusCode } = e;
123
+ if (statusCode && statusCode >= 400 && statusCode < 500) {
124
+ throw new HttpRequestLogicException(e);
125
+ }
126
+ throw new HttpRequestIOException(e);
127
+ }
128
+ }
129
+
130
+ dumpRequest(req, asString = false) {
131
+ const getBody = (r) => {
132
+ if (r._json) {
133
+ return r.body;
134
+ }
135
+ return r.form(r.formData).body;
136
+ };
137
+ const dump = {
138
+ method: req.method,
139
+ protocol: req.uri && req.uri.protocol === 'https:' ? 'https' : 'http',
140
+ url: req.uri ? req.uri.href : null,
141
+ headers: req.headers,
142
+ body: req.req && (req._json || req.formData)
143
+ ? getBody(req) : null
144
+ };
145
+ return asString === true ? JSON.stringify(dump) : dump;
146
+ }
147
+
148
+ dumpResponse(res, asString = false) {
149
+ const dump = {
150
+ statusCode: res.statusCode,
151
+ statusMessage: res.statusMessage,
152
+ headers: res.headers,
153
+ body: res.body
154
+ };
155
+ return asString === true ? JSON.stringify(dump) : dump;
156
+ }
157
+ }
158
+
159
+ constitute.Dependencies(Config, Logger)(HttpClient);
160
+ export default HttpClient;
@@ -0,0 +1,27 @@
1
+ import Cache from './cache.js';
2
+ import Config from './config.js';
3
+ import Env from './env.js';
4
+ import HttpClient from './http_client.js';
5
+ import JsonWebToken from './jwt_token.js';
6
+ import Logger from './logger.js';
7
+ import Redis from './redis.js';
8
+ import RestClient from './rest_client.js';
9
+ import Namespace from './namespace.js';
10
+ import Now from './now.js';
11
+ import ValidatorBase from './joi.js';
12
+ import EventManager from './event_manager.js';
13
+
14
+ export {
15
+ Cache,
16
+ Config,
17
+ Env,
18
+ HttpClient,
19
+ JsonWebToken,
20
+ Logger,
21
+ Redis,
22
+ RestClient,
23
+ Namespace,
24
+ Now,
25
+ ValidatorBase,
26
+ EventManager
27
+ };
@@ -0,0 +1,5 @@
1
+ export default class ServiceInterface {
2
+ getProto() {
3
+ return {};
4
+ }
5
+ }
@@ -0,0 +1,13 @@
1
+ import Joi from 'joi';
2
+ import ServiceInterface from './interface.js';
3
+
4
+ export default class ValidatorBase extends ServiceInterface {
5
+ getProto() {
6
+ return Joi;
7
+ }
8
+
9
+ getJoi() {
10
+ return Joi;
11
+ }
12
+ }
13
+