evaengine 1.0.0 → 1.0.2

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 +126 -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 +669 -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 +352 -0
  46. package/src/utils/test.js +48 -0
  47. package/src/utils/wrapper.js +8 -0
@@ -0,0 +1,89 @@
1
+ import constitute from 'constitute';
2
+ import jwt from 'jwt-simple';
3
+ import Config from './config.js';
4
+ import Redis from './redis.js';
5
+ import ServiceInterface from './interface.js';
6
+
7
+ class JsonWebToken extends ServiceInterface {
8
+ /**
9
+ * @param config {Config}
10
+ * @param redis {Redis}
11
+ */
12
+ constructor(config, redis) {
13
+ super();
14
+ this.redis = redis.getInstance();
15
+ this.config = config.get('token');
16
+ }
17
+
18
+ getProto() {
19
+ return jwt;
20
+ }
21
+
22
+ getRedis() {
23
+ return this.redis;
24
+ }
25
+
26
+ getPrefix() {
27
+ return this.config.prefix;
28
+ }
29
+
30
+ async save(uid, item) {
31
+ const toSaveItem = Object.assign({ uid }, item);
32
+ const tokenString = this.encode(toSaveItem);
33
+ const key = [this.getPrefix(), uid, tokenString.split('.').pop()].join(':');
34
+ //TODO 过期时间
35
+ await this.getRedis().set(key, JSON.stringify(toSaveItem));
36
+ return tokenString;
37
+ }
38
+
39
+ async find(tokenString) {
40
+ if (!tokenString) {
41
+ return { uid: null, expiredAt: 0 };
42
+ }
43
+ const parsedToken = this.decode(tokenString);
44
+ if (!parsedToken || !{}.hasOwnProperty.call(parsedToken, 'uid')) {
45
+ return { uid: null, expiredAt: 0 };
46
+ }
47
+ const key = [this.getPrefix(), parsedToken.uid, tokenString.split('.').pop()].join(':');
48
+ const storedToken = await this.redis.get(key);
49
+ if (!storedToken) {
50
+ return {
51
+ uid: parsedToken.uid,
52
+ expiredAt: 0
53
+ };
54
+ }
55
+ return JSON.parse(storedToken);
56
+ }
57
+
58
+ clear(tokenString) {
59
+ if (!tokenString) {
60
+ return true;
61
+ }
62
+ const key = this.getRedisKey(tokenString);
63
+ if (!key) {
64
+ return true;
65
+ }
66
+ return this.redis.del(key);
67
+ }
68
+
69
+ getRedisKey(tokenString, groupOnly = false) {
70
+ const parsedToken = this.decode(tokenString);
71
+ if (!parsedToken || !{}.hasOwnProperty.call(parsedToken, 'uid')) {
72
+ return '';
73
+ }
74
+ return groupOnly === true ?
75
+ [this.getPrefix(), parsedToken.uid].join(':') :
76
+ [this.getPrefix(), parsedToken.uid, tokenString.split('.').pop()].join(':');
77
+ }
78
+
79
+ encode(item, secret = this.config.secret) {
80
+ return jwt.encode(item, secret);
81
+ }
82
+
83
+ decode(str, secret = this.config.secret) {
84
+ return jwt.decode(str, secret);
85
+ }
86
+ }
87
+
88
+ constitute.Dependencies(Config, Redis)(JsonWebToken);
89
+ export default JsonWebToken;
@@ -0,0 +1,75 @@
1
+ import constitute from 'constitute';
2
+ import jwt from 'jwt-simple';
3
+ import _ from 'lodash';
4
+
5
+ import { RuntimeException } from '../exceptions/index.js';
6
+ import Config from './config.js';
7
+ import RestClient from '../services/rest_client.js';
8
+ import ServiceInterface from './interface.js';
9
+
10
+ class KongJsonWebToken extends ServiceInterface {
11
+ /**
12
+ * @param config {Config}
13
+ * @param restClient {RestClient}
14
+ */
15
+ constructor(config, restClient) {
16
+ super();
17
+ this.restClient = restClient;
18
+ this.config = config.get('token');
19
+ if (!_.get(this.config, 'kong.endpoint')) {
20
+ throw new RuntimeException('config item `token.kong.endpoint` can not be null');
21
+ }
22
+ }
23
+
24
+ getProto() {
25
+ return jwt;
26
+ }
27
+
28
+ async save(uid, item) {
29
+ const toSaveItem = Object.assign({ uid }, item);
30
+ const tokenString = this.encode(toSaveItem);
31
+ await this.restClient.request({
32
+ url: `${this.config.kong.endpoint}/rbac/credentials`,
33
+ method: 'post',
34
+ body: {
35
+ custom_id: uid.toString(),
36
+ username: item.username || null,
37
+ key: tokenString,
38
+ expired_at: item.expiredAt ? item.expiredAt * 1000 : null
39
+ }
40
+ });
41
+ return tokenString;
42
+ }
43
+
44
+ async find(tokenString) {
45
+ if (!tokenString) {
46
+ return { uid: null, expiredAt: 0 };
47
+ }
48
+ const parsedToken = this.decode(tokenString);
49
+ if (!parsedToken || !{}.hasOwnProperty.call(parsedToken, 'uid')) {
50
+ return { uid: null, expiredAt: 0 };
51
+ }
52
+ return parsedToken;
53
+ }
54
+
55
+ clear(tokenString) {
56
+ if (!tokenString) {
57
+ return true;
58
+ }
59
+ return this.restClient.request({
60
+ url: `${this.config.kong.endpoint}/rbac/credentials/${tokenString}`,
61
+ method: 'delete'
62
+ });
63
+ }
64
+
65
+ encode(item, secret = this.config.secret) {
66
+ return jwt.encode(item, secret);
67
+ }
68
+
69
+ decode(str, secret = this.config.secret) {
70
+ return jwt.decode(str, secret);
71
+ }
72
+ }
73
+
74
+ constitute.Dependencies(Config, RestClient)(KongJsonWebToken);
75
+ export default KongJsonWebToken;
@@ -0,0 +1,148 @@
1
+ import constitute from 'constitute';
2
+ import moment from 'moment-timezone';
3
+ import winston from 'winston';
4
+ import { inspect } from 'util';
5
+ import Env from './env.js';
6
+ import Config from './config.js';
7
+ import Namespace from './namespace.js';
8
+ import ServiceInterface from './interface.js';
9
+
10
+
11
+ class Logger extends ServiceInterface {
12
+ /**
13
+ * @param env {Env}
14
+ * @param config {Config}
15
+ * @param namespace {Namespace}
16
+ */
17
+ constructor(env, config, namespace) {
18
+ super();
19
+ this.env = env;
20
+ this.config = config;
21
+ this.namespace = namespace;
22
+
23
+ let level = env.isProduction() ? 'info' : 'debug';
24
+ if (process.env.LOG_LEVEL) {
25
+ level = process.env.LOG_LEVEL;
26
+ }
27
+ this.level = level;
28
+ winston.level = level;
29
+ this.instance = null;
30
+ this.label = null;
31
+ this.logfile = null;
32
+ }
33
+
34
+ getProto() {
35
+ return winston;
36
+ }
37
+
38
+ getWinston() {
39
+ return winston;
40
+ }
41
+
42
+ setLogFile(logfile) {
43
+ this.logfile = logfile;
44
+ return this;
45
+ }
46
+
47
+ setLabel(label) {
48
+ this.label = label;
49
+ return this;
50
+ }
51
+
52
+ setLevel(level) {
53
+ this.level = level;
54
+ return this;
55
+ }
56
+
57
+ /**
58
+ * @returns {winston.Logger}
59
+ */
60
+ getInstance() {
61
+ if (this.instance) {
62
+ return this.instance;
63
+ }
64
+ const logPath = this.logfile || this.config.get('logger.file');
65
+ this.instance = this.factory(logPath);
66
+ return this.instance;
67
+ }
68
+
69
+ /**
70
+ * @param logPath
71
+ * @param key
72
+ * @param level
73
+ * @returns {winston.Logger}
74
+ */
75
+ factory(logPath, key = 'global', level = this.level) {
76
+ const timestamp = () => moment().format();
77
+ return logPath ? winston.createLogger({
78
+ transports: [
79
+ new (winston.transports.Console)({
80
+ name: `${key}-console`,
81
+ timestamp,
82
+ level,
83
+ label: this.label
84
+ }),
85
+ new (winston.transports.File)({
86
+ name: `${key}-file`,
87
+ timestamp,
88
+ json: false,
89
+ level,
90
+ label: this.label,
91
+ filename: logPath
92
+ })
93
+ ]
94
+ }) : winston.createLogger({
95
+ transports: [
96
+ new (winston.transports.Console)({
97
+ name: `${key}-console`,
98
+ timestamp,
99
+ level,
100
+ label: this.label,
101
+ colorize: !this.env.isProduction(),
102
+ prettyPrint: !this.env.isProduction()
103
+ })
104
+ ]
105
+ });
106
+ }
107
+
108
+ populateTraceId(args) {
109
+ if (!this.namespace.get('tracer')) {
110
+ return args;
111
+ }
112
+ const { spanId, traceId } = this.namespace.get('tracer') || {};
113
+ if (spanId) {
114
+ args.push(spanId);
115
+ }
116
+ if (spanId !== traceId) {
117
+ args.push(traceId);
118
+ }
119
+ return args;
120
+ }
121
+
122
+ debug(...args) {
123
+ return this.getInstance().debug(...this.populateTraceId(args));
124
+ }
125
+
126
+ verbose(...args) {
127
+ return this.getInstance().verbose(...this.populateTraceId(args));
128
+ }
129
+
130
+ info(...args) {
131
+ return this.getInstance().info(...this.populateTraceId(args));
132
+ }
133
+
134
+ warn(...args) {
135
+ return this.getInstance().warn(...this.populateTraceId(args));
136
+ }
137
+
138
+ error(...args) {
139
+ return this.getInstance().error(...this.populateTraceId(args));
140
+ }
141
+
142
+ dump(obj) {
143
+ return this.debug(inspect(obj, { depth: null, colors: true }));
144
+ }
145
+ }
146
+
147
+ constitute.Dependencies(Env, Config, Namespace)(Logger);
148
+ export default Logger;
@@ -0,0 +1,176 @@
1
+ import constitute from 'constitute';
2
+ import { createNamespace, getNamespace, destroyNamespace, reset } from 'continuation-local-storage';
3
+ import Config from './config.js';
4
+ import { OperationUnsupportedException } from '../exceptions/index.js';
5
+ import ServiceInterface from './interface.js';
6
+
7
+ const stores = {};
8
+
9
+ export class Store {
10
+ get() {
11
+ return null;
12
+ }
13
+
14
+ set() {
15
+ return this;
16
+ }
17
+
18
+ bind() {
19
+ return this;
20
+ }
21
+
22
+ reset() {
23
+ return this;
24
+ }
25
+
26
+ active() {
27
+ }
28
+
29
+ run(callback) {
30
+ return callback();
31
+ }
32
+
33
+ bindEmitter() {
34
+ return this;
35
+ }
36
+
37
+ getContext() {
38
+ throw new OperationUnsupportedException('Not able to get namespace context when it be disabled');
39
+ }
40
+
41
+ createContext() {
42
+ }
43
+ }
44
+
45
+ export class NullStore extends Store {
46
+ }
47
+
48
+ export class NsStore extends Store {
49
+ constructor(name) {
50
+ super();
51
+ this.name = name;
52
+ createNamespace(name);
53
+ }
54
+
55
+ get(key) {
56
+ return getNamespace(this.name).get(key);
57
+ }
58
+
59
+ set(key, value) {
60
+ getNamespace(this.name).set(key, value);
61
+ return this;
62
+ }
63
+
64
+ bind(...args) {
65
+ return getNamespace(this.name).bind(...args);
66
+ }
67
+
68
+ active() {
69
+ return getNamespace(this.name).active();
70
+ }
71
+
72
+ run(...args) {
73
+ return getNamespace(this.name).run(...args);
74
+ }
75
+
76
+ bindEmitter(...args) {
77
+ return getNamespace(this.name).bindEmitter(...args);
78
+ }
79
+
80
+ getContext() {
81
+ return getNamespace(this.name);
82
+ }
83
+
84
+ createContext() {
85
+ return getNamespace(this.name).createContext();
86
+ }
87
+
88
+ reset() {
89
+ reset(this.name);
90
+ return this;
91
+ }
92
+ }
93
+
94
+ class Namespace extends ServiceInterface {
95
+ /**
96
+ * @param config {Config}
97
+ */
98
+ constructor(config) {
99
+ super();
100
+ this.config = config.get('namespace');
101
+ this.defaultName = config.defaultName || 'eva.ns';
102
+ this.store = null;
103
+ this.name = null;
104
+ }
105
+
106
+ isEnabled() {
107
+ return this.config.enable;
108
+ }
109
+
110
+ getDefaultName() {
111
+ return this.defaultName;
112
+ }
113
+
114
+ setDefaultName(name) {
115
+ this.defaultName = name;
116
+ return this;
117
+ }
118
+
119
+ getName() {
120
+ return this.name;
121
+ }
122
+
123
+ /**
124
+ * @returns {Store}
125
+ */
126
+ getStore() {
127
+ if ({}.hasOwnProperty.call(stores, this.name)) {
128
+ return stores[this.name];
129
+ }
130
+ stores[this.name] = this.config.enable === true ?
131
+ new NsStore(this.name) : new NullStore(this.name);
132
+ return stores[this.name];
133
+ }
134
+
135
+ destroy(name) {
136
+ destroyNamespace(name);
137
+ delete stores[name];
138
+ return this;
139
+ }
140
+
141
+ use(ns) {
142
+ this.name = ns || this.defaultName;
143
+ return this.getStore();
144
+ }
145
+
146
+ get(key) {
147
+ return this.use().get(key);
148
+ }
149
+
150
+ set(key, value) {
151
+ return this.use().set(key, value);
152
+ }
153
+
154
+ bind(...args) {
155
+ return this.use().bind(...args);
156
+ }
157
+
158
+ active() {
159
+ return this.use().active();
160
+ }
161
+
162
+ run(...args) {
163
+ return this.use().run(...args);
164
+ }
165
+
166
+ bindEmitter(...args) {
167
+ return this.use().bindEmitter(...args);
168
+ }
169
+
170
+ createContext() {
171
+ return this.use().createContext();
172
+ }
173
+ }
174
+
175
+ constitute.Dependencies(Config)(Namespace);
176
+ export default Namespace;
@@ -0,0 +1,49 @@
1
+ import constitute from 'constitute';
2
+ import moment from 'moment-timezone';
3
+ import { getTimestamp, getDatabaseDatetime } from '../utils/datetime.js';
4
+ import Logger from './logger.js';
5
+ import ServiceInterface from './interface.js';
6
+
7
+ class Now extends ServiceInterface {
8
+ /**
9
+ * @param {Logger} logger
10
+ */
11
+ constructor(logger) {
12
+ super();
13
+ this.logger = logger;
14
+ this.now = null;
15
+ }
16
+
17
+ setNow(now) {
18
+ if (typeof now === 'number') {
19
+ this.now = now;
20
+ } else if (now instanceof moment) {
21
+ this.now = now.unix();
22
+ } else {
23
+ this.now = moment(now).unix();
24
+ }
25
+ this.logger.warn('Now has been force changed to %s', moment.unix(this.now));
26
+ return this;
27
+ }
28
+
29
+ clear() {
30
+ this.now = null;
31
+ return this;
32
+ }
33
+
34
+ getTimestamp() {
35
+ return this.now || getTimestamp();
36
+ }
37
+
38
+ getMoment() {
39
+ return this.now ? moment.unix(this.now) : moment();
40
+ }
41
+
42
+ getDatabaseDatetime() {
43
+ return this.now ? moment.unix(this.now).format('YYYY-MM-DD HH:mm:ss') : getDatabaseDatetime();
44
+ }
45
+ }
46
+
47
+ constitute.Dependencies(Logger)(Now);
48
+ export default Now;
49
+
@@ -0,0 +1,158 @@
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 KongJsonWebToken from './jwt_token_kong.js';
7
+ import Logger from './logger.js';
8
+ import Redis from './redis.js';
9
+ import RestClient from './rest_client.js';
10
+ import Namespace from './namespace.js';
11
+ import Now from './now.js';
12
+ import ValidatorBase from './joi.js';
13
+ import EventManager from './event_manager.js';
14
+ import DI from '../di.js';
15
+
16
+ export class ServiceProvider {
17
+ constructor(engine) {
18
+ this.engine = engine;
19
+ }
20
+
21
+ get name() {
22
+ return 'default';
23
+ }
24
+
25
+ register() {
26
+ }
27
+ }
28
+
29
+ export class EnvProvider extends ServiceProvider {
30
+ get name() {
31
+ return 'env';
32
+ }
33
+
34
+ register() {
35
+ DI.bindClass(this.name, Env);
36
+ }
37
+ }
38
+
39
+ export class ConfigProvider extends ServiceProvider {
40
+ get name() {
41
+ return 'config';
42
+ }
43
+
44
+ register() {
45
+ const config = DI.get(Config);
46
+ config.setPath(this.engine.getMeta().configPath);
47
+ DI.bindClass(this.name, Config, [config]);
48
+ }
49
+ }
50
+
51
+ export class LoggerProvider extends ServiceProvider {
52
+ get name() {
53
+ return 'logger';
54
+ }
55
+
56
+ register() {
57
+ const logger = DI.get(Logger);
58
+ const { mode } = this.engine.getMeta();
59
+ const loggerLabel = mode === 'web' ? mode + this.engine.getMeta().port
60
+ : process.env.CLI_NAME || 'cli';
61
+ logger.setLabel(loggerLabel);
62
+ DI.bindClass(this.name, Logger, [logger]);
63
+ }
64
+ }
65
+
66
+ export class RedisProvider extends ServiceProvider {
67
+ get name() {
68
+ return 'redis';
69
+ }
70
+
71
+ register() {
72
+ DI.bindClass(this.name, Redis);
73
+ }
74
+ }
75
+
76
+ export class JsonWebTokenProvider extends ServiceProvider {
77
+ get name() {
78
+ return 'jwt';
79
+ }
80
+
81
+ register() {
82
+ if (DI.get('config').get('token.provider') === 'kong') {
83
+ DI.bindClass(this.name, KongJsonWebToken);
84
+ } else {
85
+ DI.bindClass(this.name, JsonWebToken);
86
+ }
87
+ }
88
+ }
89
+
90
+ export class HttpClientProvider extends ServiceProvider {
91
+ get name() {
92
+ return 'http_client';
93
+ }
94
+
95
+ register() {
96
+ DI.bindClass(this.name, HttpClient);
97
+ }
98
+ }
99
+
100
+ export class RestClientProvider extends ServiceProvider {
101
+ get name() {
102
+ return 'rest_client';
103
+ }
104
+
105
+ register() {
106
+ DI.bindClass(this.name, RestClient);
107
+ }
108
+ }
109
+
110
+ export class CacheProvider extends ServiceProvider {
111
+ get name() {
112
+ return 'cache';
113
+ }
114
+
115
+ register() {
116
+ DI.bindClass(this.name, Cache);
117
+ }
118
+ }
119
+
120
+ export class NamespaceProvider extends ServiceProvider {
121
+ get name() {
122
+ return 'namespace';
123
+ }
124
+
125
+ register() {
126
+ DI.bindClass(this.name, Namespace);
127
+ }
128
+ }
129
+
130
+ export class ValidatorBaseProvider extends ServiceProvider {
131
+ get name() {
132
+ return 'validator_base';
133
+ }
134
+
135
+ register() {
136
+ DI.bindClass(this.name, ValidatorBase);
137
+ }
138
+ }
139
+
140
+ export class EventManagerProvider extends ServiceProvider {
141
+ get name() {
142
+ return 'event_manager';
143
+ }
144
+
145
+ register() {
146
+ DI.bindClass(this.name, EventManager);
147
+ }
148
+ }
149
+
150
+ export class NowProvider extends ServiceProvider {
151
+ get name() {
152
+ return 'now';
153
+ }
154
+
155
+ register() {
156
+ DI.bindClass(this.name, Now);
157
+ }
158
+ }