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