@sdflc/backend-helpers 1.0.79 → 1.0.81

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 +4 -5
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
@@ -22,25 +13,27 @@ const DataCache_1 = require("./DataCache");
22
13
  const constants_1 = require("./constants");
23
14
  const DEFAULT_CHUNCK_SIZE = 2500;
24
15
  class BaseGateway {
16
+ config;
17
+ logger;
18
+ loader;
19
+ dateTime = new utils_1.DateTimeHelpers();
20
+ dateTimeNow = new Date();
25
21
  constructor(props) {
26
- var _a, _b, _c;
27
- this.dateTime = new utils_1.DateTimeHelpers();
28
- this.dateTimeNow = new Date();
29
22
  this.config = props;
30
23
  this.config.returnFields =
31
24
  Array.isArray(this.config.returnFields) && this.config.returnFields.length > 0 ? this.config.returnFields : ['*'];
32
25
  this.config.activeStatuses = Array.isArray(this.config.activeStatuses)
33
26
  ? this.config.activeStatuses
34
27
  : [utils_1.STATUSES.ACTIVE];
35
- this.config.keyPrefix = ((_a = this.config.context) === null || _a === void 0 ? void 0 : _a.keyPrefix) || this.config.keyPrefix || this.config.table;
36
- if (this.config.keyPrefix && ((_b = this.config.context) === null || _b === void 0 ? void 0 : _b.usedKeyPrefixes)) {
28
+ this.config.keyPrefix = this.config.context?.keyPrefix || this.config.keyPrefix || this.config.table;
29
+ if (this.config.keyPrefix && this.config.context?.usedKeyPrefixes) {
37
30
  if (this.config.context.usedKeyPrefixes[this.config.keyPrefix]) {
38
31
  throw new Error(`The "${this.config.keyPrefix}" is already used as the "keyPrefix" in the application. Please use another one that is not as: ${Object.keys(this.config.context.usedKeyPrefixes).join(', ')}`);
39
32
  }
40
33
  this.config.context.usedKeyPrefixes[this.config.keyPrefix] = true;
41
34
  }
42
- this.logger = (props === null || props === void 0 ? void 0 : props.logger) instanceof utils_1.Logger ? props.logger : new utils_1.Logger({ level: utils_1.LoggerLevels.WARNING });
43
- this.loader = check_types_1.default.function((_c = this.config) === null || _c === void 0 ? void 0 : _c.loader) ? this.config.loader : new DataCache_1.DataCache(this.config);
35
+ this.logger = props?.logger instanceof utils_1.Logger ? props.logger : new utils_1.Logger({ level: utils_1.LoggerLevels.WARNING });
36
+ this.loader = check_types_1.default.function(this.config?.loader) ? this.config.loader : new DataCache_1.DataCache(this.config);
44
37
  }
45
38
  getConfig() {
46
39
  return this.config;
@@ -54,215 +47,201 @@ class BaseGateway {
54
47
  return this;
55
48
  }
56
49
  setLoaderConfig(config) {
57
- this.loader = new DataCache_1.DataCache(Object.assign(Object.assign({}, this.config), config));
50
+ this.loader = new DataCache_1.DataCache({ ...this.config, ...config });
58
51
  return this;
59
52
  }
60
- generateId(args) {
61
- return __awaiter(this, void 0, void 0, function* () {
62
- return (0, uuid_1.v4)();
63
- });
53
+ async generateId(args) {
54
+ return (0, uuid_1.v4)();
64
55
  }
65
- onListFilter(query, filterParams) {
66
- return __awaiter(this, void 0, void 0, function* () {
67
- const { table, hasStatus, hasRemovedAt, hasSpace, activeStatuses, hasLang, fieldForKeyword, filterByUserField } = this.config || {};
68
- // This function should be overriden
69
- if (hasStatus) {
70
- query.whereIn(`${table}.${constants_1.FIELDS.STATUS}`, Array.isArray(filterParams === null || filterParams === void 0 ? void 0 : filterParams[constants_1.FIELDS.STATUS]) ? filterParams === null || filterParams === void 0 ? void 0 : filterParams[constants_1.FIELDS.STATUS] : (0, lodash_1.castArray)(activeStatuses));
71
- }
72
- if (hasRemovedAt) {
73
- query.whereNull(`${table}.${constants_1.FIELDS.REMOVED_AT}`);
74
- }
75
- if (hasSpace && ((filterParams === null || filterParams === void 0 ? void 0 : filterParams[constants_1.FIELDS.SPACE_ID]) != undefined || this.config.context.spaceId)) {
76
- query.where({
77
- [`${table}.${constants_1.FIELDS.SPACE_ID}`]: (filterParams === null || filterParams === void 0 ? void 0 : filterParams[constants_1.FIELDS.SPACE_ID]) != undefined ? filterParams === null || filterParams === void 0 ? void 0 : filterParams[constants_1.FIELDS.SPACE_ID] : this.config.context.spaceId,
78
- });
79
- }
80
- if (hasLang && (filterParams === null || filterParams === void 0 ? void 0 : filterParams[constants_1.FIELDS.LANG]) != undefined) {
81
- query.whereIn(`${table}.${constants_1.FIELDS.LANG}`, (0, lodash_1.castArray)(filterParams === null || filterParams === void 0 ? void 0 : filterParams[constants_1.FIELDS.LANG]));
82
- }
83
- const idField = this.getIdField();
84
- if (filterParams === null || filterParams === void 0 ? void 0 : filterParams[idField]) {
85
- query.whereIn(idField.includes('.') ? `${idField}` : `${table}.${idField}`, (0, lodash_1.castArray)(filterParams === null || filterParams === void 0 ? void 0 : filterParams[idField]));
86
- }
87
- if (fieldForKeyword && filterParams.keyword) {
88
- query.whereRaw(`${fieldForKeyword} ILIKE ?`, `%${filterParams.keyword}%`);
89
- }
90
- if (filterByUserField) {
91
- query.where({ [filterByUserField]: this.getContext().userId });
92
- }
93
- // TODO: prse filterParams and buils where clause automatically here
94
- });
56
+ async onListFilter(query, filterParams) {
57
+ const { table, hasStatus, hasRemovedAt, hasSpace, activeStatuses, hasLang, fieldForKeyword, filterByUserField } = this.config || {};
58
+ // This function should be overriden
59
+ if (hasStatus) {
60
+ query.whereIn(`${table}.${constants_1.FIELDS.STATUS}`, Array.isArray(filterParams?.[constants_1.FIELDS.STATUS]) ? filterParams?.[constants_1.FIELDS.STATUS] : (0, lodash_1.castArray)(activeStatuses));
61
+ }
62
+ if (hasRemovedAt) {
63
+ query.whereNull(`${table}.${constants_1.FIELDS.REMOVED_AT}`);
64
+ }
65
+ if (hasSpace && (filterParams?.[constants_1.FIELDS.SPACE_ID] != undefined || this.config.context.spaceId)) {
66
+ query.where({
67
+ [`${table}.${constants_1.FIELDS.SPACE_ID}`]: filterParams?.[constants_1.FIELDS.SPACE_ID] != undefined ? filterParams?.[constants_1.FIELDS.SPACE_ID] : this.config.context.spaceId,
68
+ });
69
+ }
70
+ if (hasLang && filterParams?.[constants_1.FIELDS.LANG] != undefined) {
71
+ query.whereIn(`${table}.${constants_1.FIELDS.LANG}`, (0, lodash_1.castArray)(filterParams?.[constants_1.FIELDS.LANG]));
72
+ }
73
+ const idField = this.getIdField();
74
+ if (filterParams?.[idField]) {
75
+ query.whereIn(idField.includes('.') ? `${idField}` : `${table}.${idField}`, (0, lodash_1.castArray)(filterParams?.[idField]));
76
+ }
77
+ if (fieldForKeyword && filterParams.keyword) {
78
+ query.whereRaw(`${fieldForKeyword} ILIKE ?`, `%${filterParams.keyword}%`);
79
+ }
80
+ if (filterByUserField) {
81
+ query.where({ [filterByUserField]: this.getContext().userId });
82
+ }
83
+ // TODO: prse filterParams and buils where clause automatically here
95
84
  }
96
- onUpdateFilter(query, filterParams) {
97
- return __awaiter(this, void 0, void 0, function* () {
98
- // This function should be overriden
99
- const { hasStatus, hasVersion } = this.config;
100
- const idName = this.getIdFieldUpdateRemove();
101
- let filtersAppliedQty = 0;
102
- if (filterParams[idName]) {
103
- filtersAppliedQty++;
104
- query.whereIn(idName, (0, lodash_1.castArray)(filterParams[idName]));
105
- }
106
- if (hasVersion) {
107
- if (filterParams[constants_1.FIELDS.VERSION] != null && !isNaN(filterParams[constants_1.FIELDS.VERSION])) {
108
- filtersAppliedQty++;
109
- query.where({ [constants_1.FIELDS.VERSION]: filterParams[constants_1.FIELDS.VERSION] });
110
- }
111
- }
112
- if (hasStatus) {
85
+ async onUpdateFilter(query, filterParams) {
86
+ // This function should be overriden
87
+ const { hasStatus, hasVersion } = this.config;
88
+ const idName = this.getIdFieldUpdateRemove();
89
+ let filtersAppliedQty = 0;
90
+ if (filterParams[idName]) {
91
+ filtersAppliedQty++;
92
+ query.whereIn(idName, (0, lodash_1.castArray)(filterParams[idName]));
93
+ }
94
+ if (hasVersion) {
95
+ if (filterParams[constants_1.FIELDS.VERSION] != null && !isNaN(filterParams[constants_1.FIELDS.VERSION])) {
113
96
  filtersAppliedQty++;
114
- if (Array.isArray(filterParams === null || filterParams === void 0 ? void 0 : filterParams[constants_1.FIELDS.STATUS])) {
115
- query.whereIn(constants_1.FIELDS.STATUS, filterParams === null || filterParams === void 0 ? void 0 : filterParams[constants_1.FIELDS.STATUS]);
116
- }
117
- else {
118
- query.where(constants_1.FIELDS.STATUS, '!=', utils_1.STATUSES.REMOVED);
119
- }
97
+ query.where({ [constants_1.FIELDS.VERSION]: filterParams[constants_1.FIELDS.VERSION] });
120
98
  }
121
- return filtersAppliedQty;
122
- });
123
- }
124
- onRemoveFilter(query, filterParams) {
125
- return __awaiter(this, void 0, void 0, function* () {
126
- // This function should be overriden
127
- const { hasStatus } = this.config;
128
- const arr = filterParams ? (0, lodash_1.castArray)(filterParams) : [];
129
- let filtersAppliedQty = 1;
130
- if (arr.length > 0) {
131
- filtersAppliedQty++;
132
- const idName = this.getIdFieldUpdateRemove();
133
- query = query.whereIn(idName, arr.map((item) => item[idName]));
99
+ }
100
+ if (hasStatus) {
101
+ filtersAppliedQty++;
102
+ if (Array.isArray(filterParams?.[constants_1.FIELDS.STATUS])) {
103
+ query.whereIn(constants_1.FIELDS.STATUS, filterParams?.[constants_1.FIELDS.STATUS]);
134
104
  }
135
- if (hasStatus === true) {
136
- filtersAppliedQty++;
105
+ else {
137
106
  query.where(constants_1.FIELDS.STATUS, '!=', utils_1.STATUSES.REMOVED);
138
107
  }
139
- return filtersAppliedQty;
140
- });
108
+ }
109
+ return filtersAppliedQty;
141
110
  }
142
- transformOnCreate(params) {
143
- return __awaiter(this, void 0, void 0, function* () {
144
- const { hasCreatedAt, hasCreatedBy, hasSpace, hasVersion, hasLang, localizationForField, hasUserId } = this.config;
145
- if (hasCreatedAt) {
146
- params[(0, lodash_1.camelCase)(constants_1.FIELDS.CREATED_AT)] = this.dateTime.dbFormat(this.dateTimeNow);
147
- }
148
- if (hasCreatedBy) {
149
- const createdBy = (0, lodash_1.camelCase)(constants_1.FIELDS.CREATED_BY);
150
- if (params[createdBy] === undefined) {
151
- params[createdBy] = this.getContext().userId;
152
- }
153
- }
154
- if (hasUserId) {
155
- const userId = (0, lodash_1.camelCase)(constants_1.FIELDS.USER_ID);
156
- if (params[userId] === undefined) {
157
- params[userId] = this.getContext().userId;
158
- }
159
- }
160
- if (hasSpace) {
161
- params[(0, lodash_1.camelCase)(constants_1.FIELDS.SPACE_ID)] = this.getContext().spaceId;
162
- }
163
- if (hasVersion) {
164
- params[(0, lodash_1.camelCase)(constants_1.FIELDS.VERSION)] = 0;
165
- }
166
- if (hasLang && localizationForField) {
167
- params[this.getIdField()] = (0, utils_1.buildKey)([params[(0, lodash_1.camelCase)(localizationForField)], params[(0, lodash_1.camelCase)(constants_1.FIELDS.LANG)]]);
168
- }
169
- return params;
170
- });
111
+ async onRemoveFilter(query, filterParams) {
112
+ // This function should be overriden
113
+ const { hasStatus } = this.config;
114
+ const arr = filterParams ? (0, lodash_1.castArray)(filterParams) : [];
115
+ let filtersAppliedQty = 1;
116
+ if (arr.length > 0) {
117
+ filtersAppliedQty++;
118
+ const idName = this.getIdFieldUpdateRemove();
119
+ query = query.whereIn(idName, arr.map((item) => item[idName]));
120
+ }
121
+ if (hasStatus === true) {
122
+ filtersAppliedQty++;
123
+ query.where(constants_1.FIELDS.STATUS, '!=', utils_1.STATUSES.REMOVED);
124
+ }
125
+ return filtersAppliedQty;
171
126
  }
172
- transformOnUpdate(params, where) {
173
- return __awaiter(this, void 0, void 0, function* () {
174
- const { hasUpdatedAt, hasUpdatedBy, hasVersion, hasLang, localizationForField } = this.config;
175
- if (hasUpdatedAt) {
176
- params[(0, lodash_1.camelCase)(constants_1.FIELDS.UPDATED_AT)] = this.dateTime.dbFormat(this.dateTimeNow);
177
- }
178
- if (hasUpdatedBy) {
179
- const updatedBy = (0, lodash_1.camelCase)(constants_1.FIELDS.UPDATED_BY);
180
- if (params[updatedBy] === undefined) {
181
- params[updatedBy] = this.getContext().userId;
182
- }
183
- }
184
- if (hasVersion) {
185
- const version = (0, lodash_1.camelCase)(constants_1.FIELDS.VERSION);
186
- if (params[version] != null && !isNaN(params[version])) {
187
- params[version] = params[version] + 1;
188
- }
127
+ async transformOnCreate(params) {
128
+ const { hasCreatedAt, hasCreatedBy, hasSpace, hasVersion, hasLang, localizationForField, hasUserId } = this.config;
129
+ if (hasCreatedAt) {
130
+ params[(0, lodash_1.camelCase)(constants_1.FIELDS.CREATED_AT)] = this.dateTime.dbFormat(this.dateTimeNow);
131
+ }
132
+ if (hasCreatedBy) {
133
+ const createdBy = (0, lodash_1.camelCase)(constants_1.FIELDS.CREATED_BY);
134
+ if (params[createdBy] === undefined) {
135
+ params[createdBy] = this.getContext().userId;
189
136
  }
190
- if (hasLang && localizationForField) {
191
- params[this.getIdField()] = (0, utils_1.buildKey)([params[(0, lodash_1.camelCase)(localizationForField)], params[(0, lodash_1.camelCase)(constants_1.FIELDS.LANG)]]);
137
+ }
138
+ if (hasUserId) {
139
+ const userId = (0, lodash_1.camelCase)(constants_1.FIELDS.USER_ID);
140
+ if (params[userId] === undefined) {
141
+ params[userId] = this.getContext().userId;
192
142
  }
193
- return params;
194
- });
143
+ }
144
+ if (hasSpace) {
145
+ params[(0, lodash_1.camelCase)(constants_1.FIELDS.SPACE_ID)] = this.getContext().spaceId;
146
+ }
147
+ if (hasVersion) {
148
+ params[(0, lodash_1.camelCase)(constants_1.FIELDS.VERSION)] = 0;
149
+ }
150
+ if (hasLang && localizationForField) {
151
+ params[this.getIdField()] = (0, utils_1.buildKey)([params[(0, lodash_1.camelCase)(localizationForField)], params[(0, lodash_1.camelCase)(constants_1.FIELDS.LANG)]]);
152
+ }
153
+ return params;
195
154
  }
196
- transformOnSet(params) {
197
- return __awaiter(this, void 0, void 0, function* () {
198
- const { hasCreatedAt, hasCreatedBy, hasSpace, hasUpdatedAt, hasUpdatedBy, hasVersion, hasLang, localizationForField, hasUserId, } = this.config;
199
- if (hasCreatedAt) {
200
- params[(0, lodash_1.camelCase)(constants_1.FIELDS.CREATED_AT)] = this.dateTime.dbFormat(this.dateTimeNow);
201
- }
202
- if (hasCreatedBy) {
203
- const createdBy = (0, lodash_1.camelCase)(constants_1.FIELDS.CREATED_BY);
204
- if (params[createdBy] === undefined) {
205
- params[createdBy] = this.getContext().userId;
206
- }
155
+ async transformOnUpdate(params, where) {
156
+ const { hasUpdatedAt, hasUpdatedBy, hasVersion, hasLang, localizationForField } = this.config;
157
+ if (hasUpdatedAt) {
158
+ params[(0, lodash_1.camelCase)(constants_1.FIELDS.UPDATED_AT)] = this.dateTime.dbFormat(this.dateTimeNow);
159
+ }
160
+ if (hasUpdatedBy) {
161
+ const updatedBy = (0, lodash_1.camelCase)(constants_1.FIELDS.UPDATED_BY);
162
+ if (params[updatedBy] === undefined) {
163
+ params[updatedBy] = this.getContext().userId;
207
164
  }
208
- if (hasUserId) {
209
- const userId = (0, lodash_1.camelCase)(constants_1.FIELDS.USER_ID);
210
- if (params[userId] === undefined) {
211
- params[userId] = this.getContext().userId;
212
- }
165
+ }
166
+ if (hasVersion) {
167
+ const version = (0, lodash_1.camelCase)(constants_1.FIELDS.VERSION);
168
+ if (params[version] != null && !isNaN(params[version])) {
169
+ params[version] = params[version] + 1;
213
170
  }
214
- if (hasSpace) {
215
- params[(0, lodash_1.camelCase)(constants_1.FIELDS.SPACE_ID)] = this.getContext().spaceId;
171
+ }
172
+ if (hasLang && localizationForField) {
173
+ params[this.getIdField()] = (0, utils_1.buildKey)([params[(0, lodash_1.camelCase)(localizationForField)], params[(0, lodash_1.camelCase)(constants_1.FIELDS.LANG)]]);
174
+ }
175
+ return params;
176
+ }
177
+ async transformOnSet(params) {
178
+ const { hasCreatedAt, hasCreatedBy, hasSpace, hasUpdatedAt, hasUpdatedBy, hasVersion, hasLang, localizationForField, hasUserId, } = this.config;
179
+ if (hasCreatedAt) {
180
+ params[(0, lodash_1.camelCase)(constants_1.FIELDS.CREATED_AT)] = this.dateTime.dbFormat(this.dateTimeNow);
181
+ }
182
+ if (hasCreatedBy) {
183
+ const createdBy = (0, lodash_1.camelCase)(constants_1.FIELDS.CREATED_BY);
184
+ if (params[createdBy] === undefined) {
185
+ params[createdBy] = this.getContext().userId;
216
186
  }
217
- if (hasUpdatedAt) {
218
- params[(0, lodash_1.camelCase)(constants_1.FIELDS.UPDATED_AT)] = this.dateTime.dbFormat(this.dateTimeNow);
187
+ }
188
+ if (hasUserId) {
189
+ const userId = (0, lodash_1.camelCase)(constants_1.FIELDS.USER_ID);
190
+ if (params[userId] === undefined) {
191
+ params[userId] = this.getContext().userId;
219
192
  }
220
- if (hasUpdatedBy) {
221
- const updatedBy = (0, lodash_1.camelCase)(constants_1.FIELDS.UPDATED_BY);
222
- if (params[updatedBy] === undefined) {
223
- params[updatedBy] = this.getContext().userId;
224
- }
193
+ }
194
+ if (hasSpace) {
195
+ params[(0, lodash_1.camelCase)(constants_1.FIELDS.SPACE_ID)] = this.getContext().spaceId;
196
+ }
197
+ if (hasUpdatedAt) {
198
+ params[(0, lodash_1.camelCase)(constants_1.FIELDS.UPDATED_AT)] = this.dateTime.dbFormat(this.dateTimeNow);
199
+ }
200
+ if (hasUpdatedBy) {
201
+ const updatedBy = (0, lodash_1.camelCase)(constants_1.FIELDS.UPDATED_BY);
202
+ if (params[updatedBy] === undefined) {
203
+ params[updatedBy] = this.getContext().userId;
225
204
  }
226
- if (hasVersion) {
227
- const version = (0, lodash_1.camelCase)(constants_1.FIELDS.VERSION);
228
- if (params[version] != null && !isNaN(params[version])) {
229
- params[version] = params[version] + 1;
230
- }
231
- else {
232
- params[version] = 0;
233
- }
205
+ }
206
+ if (hasVersion) {
207
+ const version = (0, lodash_1.camelCase)(constants_1.FIELDS.VERSION);
208
+ if (params[version] != null && !isNaN(params[version])) {
209
+ params[version] = params[version] + 1;
234
210
  }
235
- if (hasLang && localizationForField) {
236
- params[this.getIdField()] = (0, utils_1.buildKey)([params[(0, lodash_1.camelCase)(localizationForField)], params[(0, lodash_1.camelCase)(constants_1.FIELDS.LANG)]]);
211
+ else {
212
+ params[version] = 0;
237
213
  }
238
- return params;
239
- });
214
+ }
215
+ if (hasLang && localizationForField) {
216
+ params[this.getIdField()] = (0, utils_1.buildKey)([params[(0, lodash_1.camelCase)(localizationForField)], params[(0, lodash_1.camelCase)(constants_1.FIELDS.LANG)]]);
217
+ }
218
+ return params;
240
219
  }
241
- transformOnRemove(args) {
242
- return __awaiter(this, void 0, void 0, function* () {
243
- const { hasRemovedAt, hasRemovedAtStr, hasStatus, hasRemovedBy, hasLang, localizationForField } = this.config;
244
- const removalTime = (0, dayjs_1.default)();
245
- const removalTimeStr = removalTime.format('YYYYMMDDTHHmmssZ');
246
- const obj = Object.assign({}, (args || {}));
247
- if (hasRemovedAt) {
248
- obj[constants_1.FIELDS.REMOVED_AT] = removalTime.toDate();
249
- }
250
- if (hasRemovedAtStr === true) {
251
- obj[constants_1.FIELDS.REMOVED_AT_STR] = removalTimeStr;
252
- }
253
- if (hasStatus) {
254
- obj[constants_1.FIELDS.STATUS] = utils_1.STATUSES.REMOVED;
255
- }
256
- if (hasRemovedBy) {
257
- if (obj[constants_1.FIELDS.REMOVED_BY] === undefined) {
258
- obj[constants_1.FIELDS.REMOVED_BY] = this.getContext().userId;
259
- }
260
- }
261
- if (hasLang && localizationForField) {
262
- obj[this.getIdField()] = this.getDb().raw(`CONCAT(id, '-${removalTimeStr}')`);
220
+ async transformOnRemove(args) {
221
+ const { hasRemovedAt, hasRemovedAtStr, hasStatus, hasRemovedBy, hasLang, localizationForField } = this.config;
222
+ const removalTime = (0, dayjs_1.default)();
223
+ const removalTimeStr = removalTime.format('YYYYMMDDTHHmmssZ');
224
+ const obj = {
225
+ ...(args || {}),
226
+ };
227
+ if (hasRemovedAt) {
228
+ obj[constants_1.FIELDS.REMOVED_AT] = removalTime.toDate();
229
+ }
230
+ if (hasRemovedAtStr === true) {
231
+ obj[constants_1.FIELDS.REMOVED_AT_STR] = removalTimeStr;
232
+ }
233
+ if (hasStatus) {
234
+ obj[constants_1.FIELDS.STATUS] = utils_1.STATUSES.REMOVED;
235
+ }
236
+ if (hasRemovedBy) {
237
+ if (obj[constants_1.FIELDS.REMOVED_BY] === undefined) {
238
+ obj[constants_1.FIELDS.REMOVED_BY] = this.getContext().userId;
263
239
  }
264
- return obj;
265
- });
240
+ }
241
+ if (hasLang && localizationForField) {
242
+ obj[this.getIdField()] = this.getDb().raw(`CONCAT(id, '-${removalTimeStr}')`);
243
+ }
244
+ return obj;
266
245
  }
267
246
  getRequestId() {
268
247
  return this.config.context.requestId;
@@ -277,8 +256,7 @@ class BaseGateway {
277
256
  return this.config.db;
278
257
  }
279
258
  getBuilder() {
280
- var _a;
281
- return (_a = this.getDb()) === null || _a === void 0 ? void 0 : _a.getBuilder(this.config.table);
259
+ return this.getDb()?.getBuilder(this.config.table);
282
260
  }
283
261
  getIdField() {
284
262
  return this.config.idField || constants_1.ID_FIELD;
@@ -286,129 +264,110 @@ class BaseGateway {
286
264
  getIdFieldUpdateRemove() {
287
265
  return this.config.idFieldUpdateRemove || this.config.idField || constants_1.ID_FIELD;
288
266
  }
289
- get(id) {
290
- return __awaiter(this, void 0, void 0, function* () {
291
- return this.loader.load(id);
292
- });
267
+ async get(id) {
268
+ return this.loader.load(id);
293
269
  }
294
- getMany(ids) {
295
- return __awaiter(this, void 0, void 0, function* () {
296
- return this.loader.loadMany(ids);
297
- });
270
+ async getMany(ids) {
271
+ return this.loader.loadMany(ids);
298
272
  }
299
- buildListQuery(args) {
300
- return __awaiter(this, void 0, void 0, function* () {
301
- const { fieldsToUse } = args || {};
302
- const query = this.getBuilder();
303
- query.select(fieldsToUse);
304
- return { query };
305
- });
273
+ async buildListQuery(args) {
274
+ const { fieldsToUse } = args || {};
275
+ const query = this.getBuilder();
276
+ query.select(fieldsToUse);
277
+ return { query };
306
278
  }
307
- list(args) {
308
- return __awaiter(this, void 0, void 0, function* () {
309
- const { filter, params, useCache } = args || {};
310
- const { limit, offset, sortBy } = this.getDb().createLimitOffsetSortBy(params, this.config.defaultSorting || []);
311
- if (!this.config.table) {
312
- return [];
313
- }
314
- const shouldUseCache = useCache != null ? useCache : !this.config.noCache;
315
- const fieldsToUse = !shouldUseCache && Array.isArray(this.config.selectFields) ? this.config.selectFields : this.getIdField();
316
- const { query } = yield this.buildListQuery({ filter, params, fieldsToUse, useCache: shouldUseCache });
317
- yield this.onListFilter(query, filter);
318
- if (limit && !isNaN(limit) && limit > 0) {
319
- query.offset(offset).limit(limit);
320
- }
321
- if (sortBy) {
322
- query.orderBy(sortBy);
323
- }
324
- const items = yield query;
325
- const result = shouldUseCache ? yield this.getMany(items.map((row) => row.id)) : items;
326
- return result;
327
- });
279
+ async list(args) {
280
+ const { filter, params, useCache } = args || {};
281
+ const { limit, offset, sortBy } = this.getDb().createLimitOffsetSortBy(params, this.config.defaultSorting || []);
282
+ if (!this.config.table) {
283
+ return [];
284
+ }
285
+ const shouldUseCache = useCache != null ? useCache : !this.config.noCache;
286
+ const fieldsToUse = !shouldUseCache && Array.isArray(this.config.selectFields) ? this.config.selectFields : this.getIdField();
287
+ const { query } = await this.buildListQuery({ filter, params, fieldsToUse, useCache: shouldUseCache });
288
+ await this.onListFilter(query, filter);
289
+ if (limit && !isNaN(limit) && limit > 0) {
290
+ query.offset(offset).limit(limit);
291
+ }
292
+ if (sortBy) {
293
+ query.orderBy(sortBy);
294
+ }
295
+ const items = await query;
296
+ const result = shouldUseCache ? await this.getMany(items.map((row) => row.id)) : items;
297
+ return result;
328
298
  }
329
- create(args) {
330
- return __awaiter(this, void 0, void 0, function* () {
331
- var _a;
332
- const objects = (0, lodash_1.castArray)(args);
333
- if (!args || objects.length === 0) {
334
- return [];
335
- }
336
- for (let idx = 0, len = objects.length; idx < len; ++idx) {
337
- const object = objects[idx];
338
- const id = yield this.generateId(object);
339
- objects[idx] = yield this.transformOnCreate(Object.assign({ id }, object));
340
- //objects.push(obj);
341
- }
342
- const result = [];
343
- const chunks = (0, utils_1.arrToChunks)(objects, ((_a = this.config) === null || _a === void 0 ? void 0 : _a.insertChunkSize) || DEFAULT_CHUNCK_SIZE);
344
- for (let idx = 0, len = chunks.length; idx < len; ++idx) {
345
- const items = yield this.getBuilder().insert(chunks[idx]).returning(this.config.returnFields);
346
- result.push(...items);
347
- }
348
- return result;
349
- });
299
+ async create(args) {
300
+ const objects = (0, lodash_1.castArray)(args);
301
+ if (!args || objects.length === 0) {
302
+ return [];
303
+ }
304
+ for (let idx = 0, len = objects.length; idx < len; ++idx) {
305
+ const object = objects[idx];
306
+ const id = await this.generateId(object);
307
+ objects[idx] = await this.transformOnCreate({ id, ...object });
308
+ //objects.push(obj);
309
+ }
310
+ const result = [];
311
+ const chunks = (0, utils_1.arrToChunks)(objects, this.config?.insertChunkSize || DEFAULT_CHUNCK_SIZE);
312
+ for (let idx = 0, len = chunks.length; idx < len; ++idx) {
313
+ const items = await this.getBuilder().insert(chunks[idx]).returning(this.config.returnFields);
314
+ result.push(...items);
315
+ }
316
+ return result;
350
317
  }
351
- update(where, params) {
352
- return __awaiter(this, void 0, void 0, function* () {
353
- const object = yield this.transformOnUpdate(params, where);
354
- const query = this.getBuilder().update(object).returning(this.config.returnFields);
355
- const filtersAppliedQty = yield this.onUpdateFilter(query, where);
356
- if (filtersAppliedQty == null || filtersAppliedQty <= 0) {
357
- throw new Error(`Failed to update the table '${this.config.table}' as none of filters applied: ${JSON.stringify(where, null, 2)}`);
358
- }
359
- const items = yield query;
360
- if (items.length > 0 && this.config.noCache !== true) {
361
- items.forEach((item) => this.loader.clear(item[this.getIdField()]));
362
- }
363
- return items;
364
- });
318
+ async update(where, params) {
319
+ const object = await this.transformOnUpdate(params, where);
320
+ const query = this.getBuilder().update(object).returning(this.config.returnFields);
321
+ const filtersAppliedQty = await this.onUpdateFilter(query, where);
322
+ if (filtersAppliedQty == null || filtersAppliedQty <= 0) {
323
+ throw new Error(`Failed to update the table '${this.config.table}' as none of filters applied: ${JSON.stringify(where, null, 2)}`);
324
+ }
325
+ const items = await query;
326
+ if (items.length > 0 && this.config.noCache !== true) {
327
+ items.forEach((item) => this.loader.clear(item[this.getIdField()]));
328
+ }
329
+ return items;
365
330
  }
366
- updateMany(params) {
367
- return __awaiter(this, void 0, void 0, function* () {
368
- if (!Array.isArray(params)) {
369
- params = [params];
370
- }
371
- const results = [];
372
- for (let idx = 0, len = params.length; idx < len; ++idx) {
373
- const item = params[idx];
374
- const items = yield this.update(item.where, item.params);
375
- results.push(...items);
376
- }
377
- if (results.length > 0 && this.config.noCache !== true) {
378
- results.forEach((item) => this.loader.clear(item[this.getIdField()]));
379
- }
380
- return results;
381
- });
331
+ async updateMany(params) {
332
+ if (!Array.isArray(params)) {
333
+ params = [params];
334
+ }
335
+ const results = [];
336
+ for (let idx = 0, len = params.length; idx < len; ++idx) {
337
+ const item = params[idx];
338
+ const items = await this.update(item.where, item.params);
339
+ results.push(...items);
340
+ }
341
+ if (results.length > 0 && this.config.noCache !== true) {
342
+ results.forEach((item) => this.loader.clear(item[this.getIdField()]));
343
+ }
344
+ return results;
382
345
  }
383
- increment(where, params) {
384
- return __awaiter(this, void 0, void 0, function* () {
385
- const object = yield this.transformOnUpdate(params, where);
386
- const query = this.getBuilder().increment(object).returning(this.config.returnFields);
387
- const filtersAppliedQty = yield this.onUpdateFilter(query, where);
388
- if (filtersAppliedQty == null || filtersAppliedQty <= 0) {
389
- throw new Error(`Failed to update the table '${this.config.table}' as none of filters applied: ${JSON.stringify(where, null, 2)}`);
390
- }
391
- const items = yield query;
392
- if (items.length > 0 && this.config.noCache !== true) {
393
- items.forEach((item) => this.loader.clear(item[this.getIdField()]));
394
- }
395
- return items;
396
- });
346
+ async increment(where, params) {
347
+ const object = await this.transformOnUpdate(params, where);
348
+ const query = this.getBuilder().increment(object).returning(this.config.returnFields);
349
+ const filtersAppliedQty = await this.onUpdateFilter(query, where);
350
+ if (filtersAppliedQty == null || filtersAppliedQty <= 0) {
351
+ throw new Error(`Failed to update the table '${this.config.table}' as none of filters applied: ${JSON.stringify(where, null, 2)}`);
352
+ }
353
+ const items = await query;
354
+ if (items.length > 0 && this.config.noCache !== true) {
355
+ items.forEach((item) => this.loader.clear(item[this.getIdField()]));
356
+ }
357
+ return items;
397
358
  }
398
- decrement(where, params) {
399
- return __awaiter(this, void 0, void 0, function* () {
400
- const object = yield this.transformOnUpdate(params, where);
401
- const query = this.getBuilder().decrement(object).returning(this.config.returnFields);
402
- const filtersAppliedQty = yield this.onUpdateFilter(query, where);
403
- if (filtersAppliedQty == null || filtersAppliedQty <= 0) {
404
- throw new Error(`Failed to update the table '${this.config.table}' as none of filters applied: ${JSON.stringify(where, null, 2)}`);
405
- }
406
- const items = yield query;
407
- if (items.length > 0 && this.config.noCache !== true) {
408
- items.forEach((item) => this.loader.clear(item[this.getIdField()]));
409
- }
410
- return items;
411
- });
359
+ async decrement(where, params) {
360
+ const object = await this.transformOnUpdate(params, where);
361
+ const query = this.getBuilder().decrement(object).returning(this.config.returnFields);
362
+ const filtersAppliedQty = await this.onUpdateFilter(query, where);
363
+ if (filtersAppliedQty == null || filtersAppliedQty <= 0) {
364
+ throw new Error(`Failed to update the table '${this.config.table}' as none of filters applied: ${JSON.stringify(where, null, 2)}`);
365
+ }
366
+ const items = await query;
367
+ if (items.length > 0 && this.config.noCache !== true) {
368
+ items.forEach((item) => this.loader.clear(item[this.getIdField()]));
369
+ }
370
+ return items;
412
371
  }
413
372
  /**
414
373
  * Inserts or updates data in the database.
@@ -417,66 +376,61 @@ class BaseGateway {
417
376
  * @param params Array of objects to update or create
418
377
  * @returns Array of updated or inserted objects
419
378
  */
420
- set(params) {
421
- return __awaiter(this, void 0, void 0, function* () {
422
- var _a;
423
- const { hasCreatedAt, hasCreatedBy, hasSpace, mergeFields } = this.config || {};
424
- const objects = (0, lodash_1.castArray)(params);
425
- if (!params || objects.length === 0) {
426
- return [];
427
- }
428
- const skipFields = [];
429
- if (hasCreatedAt) {
430
- skipFields.push(constants_1.FIELDS.CREATED_AT);
431
- }
432
- if (hasCreatedBy) {
433
- skipFields.push(constants_1.FIELDS.CREATED_BY);
434
- }
435
- if (hasSpace) {
436
- skipFields.push(constants_1.FIELDS.SPACE_ID);
437
- }
438
- for (let idx = 0, len = objects.length; idx < len; ++idx) {
439
- const object = objects[idx];
440
- objects[idx] = yield this.transformOnSet(object);
441
- if (objects[idx][this.getIdField()] == null) {
442
- objects[idx][this.getIdField()] = yield this.generateId(object);
443
- }
444
- }
445
- const fields = Array.isArray(mergeFields) ? mergeFields : Object.keys(objects[0]);
446
- const result = [];
447
- const chunks = (0, utils_1.arrToChunks)(objects, ((_a = this.config) === null || _a === void 0 ? void 0 : _a.insertChunkSize) || DEFAULT_CHUNCK_SIZE);
448
- for (let idx = 0, len = chunks.length; idx < len; ++idx) {
449
- const items = yield this.getBuilder()
450
- .insert(chunks[idx])
451
- .returning(this.config.returnFields)
452
- .onConflict(this.config.setFields || this.getIdField())
453
- .merge((0, lodash_1.pullAll)(fields, skipFields));
454
- result.push(...items);
379
+ async set(params) {
380
+ const { hasCreatedAt, hasCreatedBy, hasSpace, mergeFields } = this.config || {};
381
+ const objects = (0, lodash_1.castArray)(params);
382
+ if (!params || objects.length === 0) {
383
+ return [];
384
+ }
385
+ const skipFields = [];
386
+ if (hasCreatedAt) {
387
+ skipFields.push(constants_1.FIELDS.CREATED_AT);
388
+ }
389
+ if (hasCreatedBy) {
390
+ skipFields.push(constants_1.FIELDS.CREATED_BY);
391
+ }
392
+ if (hasSpace) {
393
+ skipFields.push(constants_1.FIELDS.SPACE_ID);
394
+ }
395
+ for (let idx = 0, len = objects.length; idx < len; ++idx) {
396
+ const object = objects[idx];
397
+ objects[idx] = await this.transformOnSet(object);
398
+ if (objects[idx][this.getIdField()] == null) {
399
+ objects[idx][this.getIdField()] = await this.generateId(object);
455
400
  }
456
- return result;
457
- });
401
+ }
402
+ const fields = Array.isArray(mergeFields) ? mergeFields : Object.keys(objects[0]);
403
+ const result = [];
404
+ const chunks = (0, utils_1.arrToChunks)(objects, this.config?.insertChunkSize || DEFAULT_CHUNCK_SIZE);
405
+ for (let idx = 0, len = chunks.length; idx < len; ++idx) {
406
+ const items = await this.getBuilder()
407
+ .insert(chunks[idx])
408
+ .returning(this.config.returnFields)
409
+ .onConflict(this.config.setFields || this.getIdField())
410
+ .merge((0, lodash_1.pullAll)(fields, skipFields));
411
+ result.push(...items);
412
+ }
413
+ return result;
458
414
  }
459
- remove(where) {
460
- return __awaiter(this, void 0, void 0, function* () {
461
- const { hardRemove } = this.config || {};
462
- const query = this.getBuilder();
463
- if (hardRemove) {
464
- query.delete(this.config.returnFields);
465
- }
466
- else {
467
- const object = yield this.transformOnRemove();
468
- query.update(object).returning(this.config.returnFields);
469
- }
470
- const filtersAppliedQty = yield this.onRemoveFilter(query, where);
471
- if (filtersAppliedQty == null || filtersAppliedQty <= 0) {
472
- throw new Error(`Failed to remove records in the table '${this.config.table}' as none of filters applied: ${JSON.stringify(where, null, 2)}`);
473
- }
474
- const items = yield query;
475
- if (items.length > 0 && this.config.noCache !== true) {
476
- items.forEach((item) => this.loader.clear(item[this.getIdField()]));
477
- }
478
- return items;
479
- });
415
+ async remove(where) {
416
+ const { hardRemove } = this.config || {};
417
+ const query = this.getBuilder();
418
+ if (hardRemove) {
419
+ query.delete(this.config.returnFields);
420
+ }
421
+ else {
422
+ const object = await this.transformOnRemove();
423
+ query.update(object).returning(this.config.returnFields);
424
+ }
425
+ const filtersAppliedQty = await this.onRemoveFilter(query, where);
426
+ if (filtersAppliedQty == null || filtersAppliedQty <= 0) {
427
+ throw new Error(`Failed to remove records in the table '${this.config.table}' as none of filters applied: ${JSON.stringify(where, null, 2)}`);
428
+ }
429
+ const items = await query;
430
+ if (items.length > 0 && this.config.noCache !== true) {
431
+ items.forEach((item) => this.loader.clear(item[this.getIdField()]));
432
+ }
433
+ return items;
480
434
  }
481
435
  }
482
436
  exports.BaseGateway = BaseGateway;