@sdflc/backend-helpers 1.0.79 → 1.0.80

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 (37) hide show
  1. package/build/BaseCore.js +496 -600
  2. package/build/BaseGateway.js +331 -377
  3. package/build/DataCache.js +16 -19
  4. package/build/Database.js +55 -74
  5. package/build/DbMigratorAndSeeder.js +88 -114
  6. package/build/RedisDataLoader.js +153 -184
  7. package/build/apiContext.js +35 -33
  8. package/build/baseController.js +9 -16
  9. package/build/commonValidators.js +22 -31
  10. package/build/configBulder.js +5 -1
  11. package/build/dbHelpers.js +19 -29
  12. package/build/dbSeeder.js +11 -20
  13. package/build/dbTableHelpers.js +10 -10
  14. package/build/downloadHelpers.js +15 -25
  15. package/build/esm/BaseCore.js +496 -600
  16. package/build/esm/BaseGateway.js +331 -377
  17. package/build/esm/DataCache.js +16 -19
  18. package/build/esm/Database.js +55 -74
  19. package/build/esm/DbMigratorAndSeeder.js +88 -114
  20. package/build/esm/RedisDataLoader.js +153 -184
  21. package/build/esm/apiContext.js +35 -33
  22. package/build/esm/baseController.js +9 -16
  23. package/build/esm/commonValidators.js +22 -31
  24. package/build/esm/configBulder.js +5 -1
  25. package/build/esm/dbHelpers.js +19 -29
  26. package/build/esm/dbSeeder.js +11 -20
  27. package/build/esm/dbTableHelpers.js +10 -10
  28. package/build/esm/downloadHelpers.js +15 -25
  29. package/build/esm/knexConfigBuilder.js +17 -7
  30. package/build/esm/passwordHelpers.js +7 -16
  31. package/build/esm/resolversHelpers.js +11 -4
  32. package/build/esm/userToken.js +2 -2
  33. package/build/knexConfigBuilder.js +17 -7
  34. package/build/passwordHelpers.js +7 -16
  35. package/build/resolversHelpers.js +11 -4
  36. package/build/userToken.js +2 -2
  37. package/package.json +2 -3
@@ -1,29 +1,35 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
1
  import { isObject, last, map, omit, pick } from 'lodash';
11
2
  import DataLoader from 'dataloader';
12
3
  import stringify from 'json-stable-stringify';
13
4
  const customOptions = ['expire', 'serialize', 'deserialize', 'cacheKeyFn'];
14
5
  const mapPromise = (promise, fn) => Promise.all(promise.map(fn));
15
6
  class RedisDataLoader {
7
+ opt;
8
+ dataLoaderOpt;
9
+ keySpace;
10
+ loader;
11
+ redisClient;
12
+ static messages = {
13
+ keyRequired: 'The "key" parameter is required',
14
+ keysArrayRequired: 'The "keys" parameter is required and should be an array',
15
+ valueRequired: 'The "value" parameter is required',
16
+ valueObjectOrNull: 'The "value" parameter must be an object or null',
17
+ keysValuesLengths: 'The "keys" and "values" are expected to be the same',
18
+ };
16
19
  constructor(redisClient, keySpace, userLoader, opt) {
17
20
  this.redisClient = redisClient;
18
21
  this.opt = pick(opt, customOptions) || {};
19
- this.dataLoaderOpt = Object.assign(Object.assign({}, omit(opt, customOptions)), { cacheKeyFn: this.opt.cacheKeyFn });
22
+ this.dataLoaderOpt = {
23
+ ...omit(opt, customOptions),
24
+ cacheKeyFn: this.opt.cacheKeyFn,
25
+ };
20
26
  this.opt.cacheKeyFn =
21
27
  typeof this.opt.cacheKeyFn === 'function'
22
28
  ? this.opt.cacheKeyFn
23
29
  : (key) => (isObject(key) ? stringify(key) : key);
24
30
  this.keySpace = keySpace ? keySpace + ':' : '';
25
- this.loader = new DataLoader((keys) => __awaiter(this, void 0, void 0, function* () {
26
- const results = yield this.rMGet(keys);
31
+ this.loader = new DataLoader(async (keys) => {
32
+ const results = await this.rMGet(keys);
27
33
  const keysToRead = [];
28
34
  const keysIdxsToRead = [];
29
35
  keys.forEach((key, idx) => {
@@ -33,14 +39,14 @@ class RedisDataLoader {
33
39
  }
34
40
  });
35
41
  if (keysToRead.length > 0) {
36
- const loadedData = yield userLoader.load(keysToRead);
37
- const data = yield this.rMSetAndGet(keysToRead, loadedData);
42
+ const loadedData = await userLoader.load(keysToRead);
43
+ const data = await this.rMSetAndGet(keysToRead, loadedData);
38
44
  keysIdxsToRead.forEach((keyIdx, idx) => {
39
45
  results[keyIdx] = data[idx];
40
46
  });
41
47
  }
42
48
  return results;
43
- }), this.dataLoaderOpt);
49
+ }, this.dataLoaderOpt);
44
50
  }
45
51
  /**
46
52
  * Adds a prefix to the passed key
@@ -55,183 +61,146 @@ class RedisDataLoader {
55
61
  * @param str String to deserialize
56
62
  * @returns
57
63
  */
58
- parse(str) {
59
- return __awaiter(this, void 0, void 0, function* () {
60
- if (str === '' || str === null) {
61
- return str;
62
- }
63
- else if (typeof this.opt.deserialize === 'function') {
64
- return yield this.opt.deserialize(str);
65
- }
66
- else {
67
- return JSON.parse(str);
68
- }
69
- });
64
+ async parse(str) {
65
+ if (str === '' || str === null) {
66
+ return str;
67
+ }
68
+ else if (typeof this.opt.deserialize === 'function') {
69
+ return await this.opt.deserialize(str);
70
+ }
71
+ else {
72
+ return JSON.parse(str);
73
+ }
70
74
  }
71
75
  /**
72
76
  * Serializes passed value to a string
73
77
  * @param value A value to be serialized
74
78
  * @returns serialized value in the form of string
75
79
  */
76
- toString(value) {
77
- return __awaiter(this, void 0, void 0, function* () {
78
- if (value === null) {
79
- return '';
80
- }
81
- else if (typeof this.opt.serialize === 'function') {
82
- return yield this.opt.serialize(value);
83
- }
84
- else if (isObject(value)) {
85
- return JSON.stringify(value);
86
- }
87
- else {
88
- throw new Error(RedisDataLoader.messages.valueObjectOrNull);
89
- }
90
- });
91
- }
92
- rSetAndGet(key, rawValue) {
93
- return __awaiter(this, void 0, void 0, function* () {
94
- const value = yield this.toString(rawValue);
95
- const fullKey = this.makeKey(key);
96
- const multi = this.redisClient.multi();
97
- multi.set(fullKey, value);
98
- if (this.opt.expire) {
80
+ async toString(value) {
81
+ if (value === null) {
82
+ return '';
83
+ }
84
+ else if (typeof this.opt.serialize === 'function') {
85
+ return await this.opt.serialize(value);
86
+ }
87
+ else if (isObject(value)) {
88
+ return JSON.stringify(value);
89
+ }
90
+ else {
91
+ throw new Error(RedisDataLoader.messages.valueObjectOrNull);
92
+ }
93
+ }
94
+ async rSetAndGet(key, rawValue) {
95
+ const value = await this.toString(rawValue);
96
+ const fullKey = this.makeKey(key);
97
+ const multi = this.redisClient.multi();
98
+ multi.set(fullKey, value);
99
+ if (this.opt.expire) {
100
+ multi.expire(fullKey, this.opt.expire);
101
+ }
102
+ multi.get(fullKey);
103
+ const replies = await multi.exec();
104
+ const lastReply = last(replies);
105
+ const result = await this.parse(lastReply);
106
+ return result;
107
+ }
108
+ async rMSetAndGet(keys, rawValues) {
109
+ const multi = this.redisClient.multi();
110
+ const fullKeys = await mapPromise(keys, (key) => this.makeKey(key));
111
+ const values = await mapPromise(rawValues, (rawValue) => this.toString(rawValue));
112
+ multi.mSet(fullKeys.reduce((acc, fullKey, idx) => {
113
+ acc.push(fullKey);
114
+ acc.push(values[idx]);
115
+ return acc;
116
+ }, []));
117
+ if (this.opt.expire) {
118
+ for (const fullKey of fullKeys) {
99
119
  multi.expire(fullKey, this.opt.expire);
100
120
  }
101
- multi.get(fullKey);
102
- const replies = yield multi.exec();
103
- const lastReply = last(replies);
104
- const result = yield this.parse(lastReply);
105
- return result;
106
- });
107
- }
108
- rMSetAndGet(keys, rawValues) {
109
- return __awaiter(this, void 0, void 0, function* () {
110
- const multi = this.redisClient.multi();
111
- const fullKeys = yield mapPromise(keys, (key) => this.makeKey(key));
112
- const values = yield mapPromise(rawValues, (rawValue) => this.toString(rawValue));
113
- multi.mSet(fullKeys.reduce((acc, fullKey, idx) => {
114
- acc.push(fullKey);
115
- acc.push(values[idx]);
116
- return acc;
117
- }, []));
118
- if (this.opt.expire) {
119
- for (const fullKey of fullKeys) {
120
- multi.expire(fullKey, this.opt.expire);
121
- }
122
- }
123
- multi.mGet(fullKeys);
124
- const replies = yield multi.exec();
125
- const lastReplies = last(replies);
126
- const result = yield mapPromise(lastReplies, (lastReply) => this.parse(lastReply));
127
- return result;
128
- });
129
- }
130
- rGet(key) {
131
- return __awaiter(this, void 0, void 0, function* () {
132
- const reply = yield this.redisClient.get(this.makeKey(key));
133
- const result = yield this.parse(reply);
134
- return result;
135
- });
136
- }
137
- rMGet(keys) {
138
- return __awaiter(this, void 0, void 0, function* () {
139
- const replies = yield this.redisClient.mGet(map(keys, (key) => this.makeKey(key)));
140
- const results = yield mapPromise(replies, (reply) => this.parse(reply));
141
- return results;
142
- });
143
- }
144
- rSet(key, rawValue) {
145
- return __awaiter(this, void 0, void 0, function* () {
146
- const value = yield this.toString(rawValue);
147
- const reply = yield this.redisClient.set(this.makeKey(key), value);
148
- const result = yield this.parse(reply);
149
- // result is expected to be OK
150
- return result;
151
- });
152
- }
153
- rMSet(keys, values) {
154
- return __awaiter(this, void 0, void 0, function* () {
155
- if (keys.length != values.length) {
156
- throw new Error(RedisDataLoader.messages.keysValuesLengths);
157
- }
158
- const multi = this.redisClient.multi();
159
- multi.mSet(keys.reduce((acc, key, idx) => {
160
- acc.push(this.makeKey(key));
161
- acc.push(values[idx]);
162
- return acc;
163
- }, []));
164
- if (this.opt.expire) {
165
- for (const key of keys) {
166
- multi.expire(key, this.opt.expire);
167
- }
168
- }
169
- // The reply is expected to be "OK"
170
- const reply = yield multi.exec();
171
- return reply;
172
- });
173
- }
174
- rDel(key) {
175
- return __awaiter(this, void 0, void 0, function* () {
176
- return yield this.redisClient.del(this.makeKey(key));
177
- });
178
- }
179
- load(key) {
180
- return __awaiter(this, void 0, void 0, function* () {
181
- if (!key) {
182
- throw new TypeError(RedisDataLoader.messages.keyRequired);
183
- }
184
- return yield this.loader.load(key);
185
- });
186
- }
187
- loadMany(keys) {
188
- return __awaiter(this, void 0, void 0, function* () {
189
- if (!Array.isArray(keys)) {
190
- throw new TypeError(RedisDataLoader.messages.keysArrayRequired);
191
- }
192
- return yield this.loader.loadMany(keys);
193
- });
194
- }
195
- prime(key, value) {
196
- return __awaiter(this, void 0, void 0, function* () {
197
- if (!key) {
198
- throw new TypeError(RedisDataLoader.messages.keyRequired);
199
- }
200
- else if (value === undefined) {
201
- throw new TypeError(RedisDataLoader.messages.valueRequired);
202
- }
203
- else {
204
- const result = yield this.rSetAndGet(key, value);
205
- return yield this.loader.clear(key).prime(key, result === '' ? null : result);
206
- }
207
- });
208
- }
209
- clear(key) {
210
- return __awaiter(this, void 0, void 0, function* () {
211
- if (!key) {
212
- throw new TypeError(RedisDataLoader.messages.keyRequired);
213
- }
214
- const resp = yield this.rDel(key);
215
- yield this.loader.clear(key);
216
- return resp;
217
- });
218
- }
219
- clearAllLocal() {
220
- return __awaiter(this, void 0, void 0, function* () {
221
- return yield this.loader.clearAll();
222
- });
223
- }
224
- clearLocal(key) {
225
- return __awaiter(this, void 0, void 0, function* () {
226
- return yield this.loader.clear(key);
227
- });
121
+ }
122
+ multi.mGet(fullKeys);
123
+ const replies = await multi.exec();
124
+ const lastReplies = last(replies);
125
+ const result = await mapPromise(lastReplies, (lastReply) => this.parse(lastReply));
126
+ return result;
127
+ }
128
+ async rGet(key) {
129
+ const reply = await this.redisClient.get(this.makeKey(key));
130
+ const result = await this.parse(reply);
131
+ return result;
132
+ }
133
+ async rMGet(keys) {
134
+ const replies = await this.redisClient.mGet(map(keys, (key) => this.makeKey(key)));
135
+ const results = await mapPromise(replies, (reply) => this.parse(reply));
136
+ return results;
137
+ }
138
+ async rSet(key, rawValue) {
139
+ const value = await this.toString(rawValue);
140
+ const reply = await this.redisClient.set(this.makeKey(key), value);
141
+ const result = await this.parse(reply);
142
+ // result is expected to be OK
143
+ return result;
144
+ }
145
+ async rMSet(keys, values) {
146
+ if (keys.length != values.length) {
147
+ throw new Error(RedisDataLoader.messages.keysValuesLengths);
148
+ }
149
+ const multi = this.redisClient.multi();
150
+ multi.mSet(keys.reduce((acc, key, idx) => {
151
+ acc.push(this.makeKey(key));
152
+ acc.push(values[idx]);
153
+ return acc;
154
+ }, []));
155
+ if (this.opt.expire) {
156
+ for (const key of keys) {
157
+ multi.expire(key, this.opt.expire);
158
+ }
159
+ }
160
+ // The reply is expected to be "OK"
161
+ const reply = await multi.exec();
162
+ return reply;
163
+ }
164
+ async rDel(key) {
165
+ return await this.redisClient.del(this.makeKey(key));
166
+ }
167
+ async load(key) {
168
+ if (!key) {
169
+ throw new TypeError(RedisDataLoader.messages.keyRequired);
170
+ }
171
+ return await this.loader.load(key);
172
+ }
173
+ async loadMany(keys) {
174
+ if (!Array.isArray(keys)) {
175
+ throw new TypeError(RedisDataLoader.messages.keysArrayRequired);
176
+ }
177
+ return await this.loader.loadMany(keys);
178
+ }
179
+ async prime(key, value) {
180
+ if (!key) {
181
+ throw new TypeError(RedisDataLoader.messages.keyRequired);
182
+ }
183
+ else if (value === undefined) {
184
+ throw new TypeError(RedisDataLoader.messages.valueRequired);
185
+ }
186
+ else {
187
+ const result = await this.rSetAndGet(key, value);
188
+ return await this.loader.clear(key).prime(key, result === '' ? null : result);
189
+ }
190
+ }
191
+ async clear(key) {
192
+ if (!key) {
193
+ throw new TypeError(RedisDataLoader.messages.keyRequired);
194
+ }
195
+ const resp = await this.rDel(key);
196
+ await this.loader.clear(key);
197
+ return resp;
198
+ }
199
+ async clearAllLocal() {
200
+ return await this.loader.clearAll();
201
+ }
202
+ async clearLocal(key) {
203
+ return await this.loader.clear(key);
228
204
  }
229
205
  }
230
- RedisDataLoader.messages = {
231
- keyRequired: 'The "key" parameter is required',
232
- keysArrayRequired: 'The "keys" parameter is required and should be an array',
233
- valueRequired: 'The "value" parameter is required',
234
- valueObjectOrNull: 'The "value" parameter must be an object or null',
235
- keysValuesLengths: 'The "keys" and "values" are expected to be the same',
236
- };
237
206
  export { RedisDataLoader };
@@ -1,12 +1,3 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
1
  import { camelCase } from 'lodash';
11
2
  import { v4 } from 'uuid';
12
3
  import check from 'check-types';
@@ -17,11 +8,11 @@ import { HEADERS } from './constants';
17
8
  * Creates a GraphQL context object with all available cores.
18
9
  * @returns {object} A context object with all available cores
19
10
  */
20
- export const createApiContext = (args) => __awaiter(void 0, void 0, void 0, function* () {
11
+ export const createApiContext = async (args) => {
21
12
  const { cores, gateways, req, res, getCoreContext, getGatewayContext, extendContext, requestId: inRequestId, } = args || {};
22
13
  const requestId = inRequestId || v4();
23
- const coreContext = check.function(getCoreContext) ? yield getCoreContext({ req }) : {};
24
- const gatewayContext = check.function(getGatewayContext) ? yield getGatewayContext({ req }) : {};
14
+ const coreContext = check.function(getCoreContext) ? await getCoreContext({ req }) : {};
15
+ const gatewayContext = check.function(getGatewayContext) ? await getGatewayContext({ req }) : {};
25
16
  const context = {
26
17
  requestId,
27
18
  cores: {},
@@ -31,23 +22,26 @@ export const createApiContext = (args) => __awaiter(void 0, void 0, void 0, func
31
22
  res,
32
23
  };
33
24
  context.cores = Object.keys(cores || {}).reduce((acc, key) => {
34
- acc[camelCase(key)] = new cores[key](Object.assign(Object.assign({}, coreContext), { context }));
25
+ acc[camelCase(key)] = new cores[key]({ ...coreContext, context });
35
26
  return acc;
36
27
  }, {});
37
28
  context.gateways = Object.keys(gateways || {}).reduce((acc, key) => {
38
- acc[camelCase(key)] = new gateways[key](Object.assign(Object.assign({}, gatewayContext), { context }));
29
+ acc[camelCase(key)] = new gateways[key]({
30
+ ...gatewayContext,
31
+ context,
32
+ });
39
33
  return acc;
40
34
  }, {});
41
35
  if (check.function(extendContext)) {
42
- yield extendContext({ context, req });
36
+ await extendContext({ context, req });
43
37
  }
44
38
  return context;
45
- });
39
+ };
46
40
  /**
47
41
  * Creates default a GraphQL context object with all avilable cores.
48
42
  * @returns {object} A context object with all available cores
49
43
  */
50
- export const createContextDefault = (args) => __awaiter(void 0, void 0, void 0, function* () {
44
+ export const createContextDefault = async (args) => {
51
45
  const { knexConfig, isProduction, logger, doAuth, spaceGw, interserviceApiKey, jwtSecret, verifyTokenArgs, dbSchema, cores, gateways, req, res, extendContext, getCoreContext, getGatewayContext, authorizationToken, db: inDb, } = args || {};
52
46
  const headers = req.headers || { noHeadersSetup: true };
53
47
  const cookies = req.cookies || { noCookiesSetup: true };
@@ -61,7 +55,7 @@ export const createContextDefault = (args) => __awaiter(void 0, void 0, void 0,
61
55
  const ipAddress = headers[HEADERS.IP_ADDRESS] || req.connection.remoteAddress;
62
56
  const acceptLanguage = headers[HEADERS.ACCEPT_LANGUAGE];
63
57
  const languages = extractLanguages(acceptLanguage);
64
- const requestedLang = headers[HEADERS.REQUESTED_LANGUAGE] || (languages === null || languages === void 0 ? void 0 : languages[0]) || 'en';
58
+ const requestedLang = headers[HEADERS.REQUESTED_LANGUAGE] || languages?.[0] || 'en';
65
59
  // const accountId = headers[HEADERS.ACCOUNT_ID];
66
60
  // const roleId = headers[HEADERS.ROLE_ID];
67
61
  // const userId = headers[HEADERS.USER_ID];
@@ -95,41 +89,49 @@ export const createContextDefault = (args) => __awaiter(void 0, void 0, void 0,
95
89
  authorizationToken,
96
90
  isExternalDb: !!inDb,
97
91
  };
98
- return yield createApiContext({
92
+ return await createApiContext({
99
93
  cores,
100
94
  gateways,
101
95
  req,
102
96
  res,
103
97
  requestId,
104
- extendContext: (_a) => __awaiter(void 0, [_a], void 0, function* ({ context, req }) {
98
+ extendContext: async ({ context, req }) => {
105
99
  context.db = db;
106
100
  Object.assign(context, sharedContext);
107
101
  if (check.function(extendContext)) {
108
- yield extendContext({ context, req });
102
+ await extendContext({ context, req });
109
103
  }
110
- }),
111
- getCoreContext: (args) => __awaiter(void 0, void 0, void 0, function* () {
104
+ },
105
+ getCoreContext: async (args) => {
112
106
  // TODO: const { req } = args;
113
107
  let extendCoreConext = {};
114
108
  if (check.function(getCoreContext)) {
115
- extendCoreConext = yield getCoreContext(args);
109
+ extendCoreConext = await getCoreContext(args);
116
110
  }
117
- return Object.assign({ db, gatewayName: '', isProduction,
111
+ return {
112
+ db,
113
+ gatewayName: '',
114
+ isProduction,
118
115
  logger,
119
116
  doAuth,
120
117
  spaceGw,
121
118
  interserviceApiKey,
122
119
  jwtSecret,
123
- verifyTokenArgs }, (extendCoreConext || {}));
124
- }),
125
- getGatewayContext: (args) => __awaiter(void 0, void 0, void 0, function* () {
120
+ verifyTokenArgs,
121
+ ...(extendCoreConext || {}),
122
+ };
123
+ },
124
+ getGatewayContext: async (args) => {
126
125
  let extendGatewayConext = {};
127
126
  if (check.function(getGatewayContext)) {
128
- extendGatewayConext = yield getGatewayContext(args);
127
+ extendGatewayConext = await getGatewayContext(args);
129
128
  }
130
- return Object.assign({ db,
129
+ return {
130
+ db,
131
131
  isProduction,
132
- logger }, (extendGatewayConext || {}));
133
- }),
132
+ logger,
133
+ ...(extendGatewayConext || {}),
134
+ };
135
+ },
134
136
  });
135
- });
137
+ };
@@ -1,12 +1,3 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
1
  import check from 'check-types';
11
2
  import { OpResult } from '@sdflc/api-helpers';
12
3
  import { Logger, LoggerLevels } from '@sdflc/utils';
@@ -14,16 +5,18 @@ import { Logger, LoggerLevels } from '@sdflc/utils';
14
5
  * Base class for REST API controllers.
15
6
  */
16
7
  class BaseController {
8
+ onResponse;
9
+ logger;
17
10
  constructor(props) {
18
- if (check.function(props === null || props === void 0 ? void 0 : props.onResponse)) {
19
- this.onResponse = props === null || props === void 0 ? void 0 : props.onResponse;
11
+ if (check.function(props?.onResponse)) {
12
+ this.onResponse = props?.onResponse;
20
13
  }
21
14
  else {
22
15
  this.onResponse = () => {
23
16
  /* TODO */
24
17
  };
25
18
  }
26
- this.logger = (props === null || props === void 0 ? void 0 : props.logger) instanceof Logger ? props.logger : new Logger({ level: LoggerLevels.ERROR });
19
+ this.logger = props?.logger instanceof Logger ? props.logger : new Logger({ level: LoggerLevels.ERROR });
27
20
  }
28
21
  init(props) {
29
22
  // const { app } = props;
@@ -36,9 +29,9 @@ class BaseController {
36
29
  * @returns HTTP response
37
30
  */
38
31
  json(method) {
39
- return (req, res, next) => __awaiter(this, void 0, void 0, function* () {
32
+ return async (req, res, next) => {
40
33
  try {
41
- const result = yield method(req, res, next);
34
+ const result = await method(req, res, next);
42
35
  if (result instanceof OpResult) {
43
36
  res.status(result.getHttpStatus()).json(result.toJS());
44
37
  }
@@ -48,13 +41,13 @@ class BaseController {
48
41
  else {
49
42
  res.status(204).json(new OpResult());
50
43
  }
51
- yield this.onResponse(req, res, next);
44
+ await this.onResponse(req, res, next);
52
45
  }
53
46
  catch (ex) {
54
47
  this.logger.log(`An exception has occured when processing REST API request on the entry point '${req.method} ${req.originalUrl}' from ${req.ip}`);
55
48
  next(ex);
56
49
  }
57
- });
50
+ };
58
51
  }
59
52
  }
60
53
  export { BaseController };