@sdflc/backend-helpers 1.0.78 → 1.0.79

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 (109) hide show
  1. package/build/BaseCore.js +0 -3
  2. package/build/BaseGateway.js +0 -2
  3. package/build/RedisDataLoader.js +7 -12
  4. package/build/commonValidators.js +3 -9
  5. package/build/esm/BaseCore.d.ts +88 -0
  6. package/build/esm/BaseCore.js +810 -0
  7. package/build/esm/BaseGateway.d.ts +49 -0
  8. package/build/esm/BaseGateway.js +476 -0
  9. package/build/esm/DataCache.d.ts +14 -0
  10. package/build/esm/DataCache.js +98 -0
  11. package/build/esm/Database.d.ts +32 -0
  12. package/build/esm/Database.js +192 -0
  13. package/build/esm/DbMigratorAndSeeder.d.ts +49 -0
  14. package/build/esm/DbMigratorAndSeeder.js +199 -0
  15. package/build/esm/RedisDataLoader.d.ts +41 -0
  16. package/build/esm/RedisDataLoader.js +237 -0
  17. package/build/esm/apiContext.d.ts +11 -0
  18. package/build/esm/apiContext.js +135 -0
  19. package/build/esm/baseController.d.ts +17 -0
  20. package/build/esm/baseController.js +60 -0
  21. package/build/esm/checkItHelpers.d.ts +3 -0
  22. package/build/esm/checkItHelpers.js +23 -0
  23. package/build/esm/commonValidators.d.ts +17 -0
  24. package/build/esm/commonValidators.js +273 -0
  25. package/build/esm/configBulder.d.ts +2 -0
  26. package/build/esm/configBulder.js +28 -0
  27. package/build/esm/constants.d.ts +30 -0
  28. package/build/esm/constants.js +69 -0
  29. package/build/esm/dbHelpers.d.ts +43 -0
  30. package/build/esm/dbHelpers.js +154 -0
  31. package/build/esm/dbSeeder.d.ts +2 -0
  32. package/build/esm/dbSeeder.js +53 -0
  33. package/build/esm/dbTableHelpers.d.ts +11 -0
  34. package/build/esm/dbTableHelpers.js +99 -0
  35. package/build/esm/downloadHelpers.d.ts +2 -0
  36. package/build/esm/downloadHelpers.js +76 -0
  37. package/build/esm/index.d.ts +21 -0
  38. package/build/esm/index.js +21 -0
  39. package/build/esm/interfaces/ApiContext.d.ts +24 -0
  40. package/build/esm/interfaces/ApiContext.js +1 -0
  41. package/build/esm/interfaces/ApiContextInterface.d.ts +12 -0
  42. package/build/esm/interfaces/ApiContextInterface.js +1 -0
  43. package/build/esm/interfaces/BaseCoreActionsInterface.d.ts +38 -0
  44. package/build/esm/interfaces/BaseCoreActionsInterface.js +1 -0
  45. package/build/esm/interfaces/BaseCoreDoAuthOnActionInterface.d.ts +12 -0
  46. package/build/esm/interfaces/BaseCoreDoAuthOnActionInterface.js +1 -0
  47. package/build/esm/interfaces/BaseCoreDoingWhatInterface.d.ts +13 -0
  48. package/build/esm/interfaces/BaseCoreDoingWhatInterface.js +1 -0
  49. package/build/esm/interfaces/BaseCorePropsInterface.d.ts +36 -0
  50. package/build/esm/interfaces/BaseCorePropsInterface.js +1 -0
  51. package/build/esm/interfaces/BaseCoreValidatorsInterface.d.ts +13 -0
  52. package/build/esm/interfaces/BaseCoreValidatorsInterface.js +1 -0
  53. package/build/esm/interfaces/BaseGatewayPropsInterface.d.ts +39 -0
  54. package/build/esm/interfaces/BaseGatewayPropsInterface.js +1 -0
  55. package/build/esm/interfaces/BuildConfigOptions.d.ts +6 -0
  56. package/build/esm/interfaces/BuildConfigOptions.js +1 -0
  57. package/build/esm/interfaces/BuildDefaultResolversOptions.d.ts +17 -0
  58. package/build/esm/interfaces/BuildDefaultResolversOptions.js +1 -0
  59. package/build/esm/interfaces/BuildListQueryArgsInterface.d.ts +6 -0
  60. package/build/esm/interfaces/BuildListQueryArgsInterface.js +1 -0
  61. package/build/esm/interfaces/CacheInterface.d.ts +15 -0
  62. package/build/esm/interfaces/CacheInterface.js +1 -0
  63. package/build/esm/interfaces/CommonValidatorArgs.d.ts +3 -0
  64. package/build/esm/interfaces/CommonValidatorArgs.js +1 -0
  65. package/build/esm/interfaces/CoreActionInterface.d.ts +14 -0
  66. package/build/esm/interfaces/CoreActionInterface.js +1 -0
  67. package/build/esm/interfaces/CreateUserTokenArgs.d.ts +11 -0
  68. package/build/esm/interfaces/CreateUserTokenArgs.js +1 -0
  69. package/build/esm/interfaces/CreateUserTokenResult.d.ts +4 -0
  70. package/build/esm/interfaces/CreateUserTokenResult.js +1 -0
  71. package/build/esm/interfaces/DatabaseOptions.d.ts +22 -0
  72. package/build/esm/interfaces/DatabaseOptions.js +1 -0
  73. package/build/esm/interfaces/DatabaseReadInterface.d.ts +14 -0
  74. package/build/esm/interfaces/DatabaseReadInterface.js +1 -0
  75. package/build/esm/interfaces/DbFieldAddDefaultInterface.d.ts +9 -0
  76. package/build/esm/interfaces/DbFieldAddDefaultInterface.js +1 -0
  77. package/build/esm/interfaces/DownloadFileArgs.d.ts +6 -0
  78. package/build/esm/interfaces/DownloadFileArgs.js +1 -0
  79. package/build/esm/interfaces/ExtractCredentialsArgs.d.ts +19 -0
  80. package/build/esm/interfaces/ExtractCredentialsArgs.js +1 -0
  81. package/build/esm/interfaces/JwtTokenSecretAndSettings.d.ts +5 -0
  82. package/build/esm/interfaces/JwtTokenSecretAndSettings.js +1 -0
  83. package/build/esm/interfaces/ListArgsInterface.d.ts +5 -0
  84. package/build/esm/interfaces/ListArgsInterface.js +1 -0
  85. package/build/esm/interfaces/LoaderInterface.d.ts +4 -0
  86. package/build/esm/interfaces/LoaderInterface.js +1 -0
  87. package/build/esm/interfaces/PaginationInterface.d.ts +7 -0
  88. package/build/esm/interfaces/PaginationInterface.js +1 -0
  89. package/build/esm/interfaces/SortItemInterface.d.ts +4 -0
  90. package/build/esm/interfaces/SortItemInterface.js +1 -0
  91. package/build/esm/interfaces/UserTokenParams.d.ts +8 -0
  92. package/build/esm/interfaces/UserTokenParams.js +1 -0
  93. package/build/esm/interfaces/VerifyUserTokenArgs.d.ts +13 -0
  94. package/build/esm/interfaces/VerifyUserTokenArgs.js +1 -0
  95. package/build/esm/interfaces/index.d.ts +28 -0
  96. package/build/esm/interfaces/index.js +27 -0
  97. package/build/esm/knexConfigBuilder.d.ts +1 -0
  98. package/build/esm/knexConfigBuilder.js +73 -0
  99. package/build/esm/passwordHelpers.d.ts +5 -0
  100. package/build/esm/passwordHelpers.js +22 -0
  101. package/build/esm/redisClient.d.ts +17 -0
  102. package/build/esm/redisClient.js +94 -0
  103. package/build/esm/resolversHelpers.d.ts +3 -0
  104. package/build/esm/resolversHelpers.js +59 -0
  105. package/build/esm/userToken.d.ts +8 -0
  106. package/build/esm/userToken.js +74 -0
  107. package/build/esm/utils.d.ts +2 -0
  108. package/build/esm/utils.js +13 -0
  109. package/package.json +13 -5
@@ -0,0 +1,49 @@
1
+ import { DateTimeHelpers, Logger } from '@sdflc/utils';
2
+ import { ApiContext, BaseGatewayPropsInterface, BuildListQueryArgsInterface, CacheInterface, ListArgsInterface, LoaderInterface } from './interfaces';
3
+ import { Database } from './Database';
4
+ declare class BaseGateway {
5
+ protected config: BaseGatewayPropsInterface;
6
+ protected logger: Logger;
7
+ protected loader: any;
8
+ protected dateTime: DateTimeHelpers;
9
+ protected dateTimeNow: Date;
10
+ constructor(props: BaseGatewayPropsInterface);
11
+ getConfig(): BaseGatewayPropsInterface;
12
+ setConfigPart(props: BaseGatewayPropsInterface): this;
13
+ setLoader(loader: LoaderInterface): this;
14
+ setLoaderConfig(config: CacheInterface): this;
15
+ generateId(args?: any): Promise<string>;
16
+ onListFilter(query: any, filterParams: any): Promise<void>;
17
+ onUpdateFilter(query: any, filterParams: any): Promise<number>;
18
+ onRemoveFilter(query: any, filterParams: any): Promise<number>;
19
+ transformOnCreate(params: any): Promise<any>;
20
+ transformOnUpdate(params: any, where?: any): Promise<any>;
21
+ transformOnSet(params: any): Promise<any>;
22
+ transformOnRemove(args?: any): Promise<any>;
23
+ getRequestId(): string;
24
+ getContext(): ApiContext;
25
+ getGateways(): any;
26
+ getDb(): Database;
27
+ getBuilder(): any;
28
+ getIdField(): string;
29
+ getIdFieldUpdateRemove(): string;
30
+ get(id: any): Promise<any>;
31
+ getMany(ids: any[]): Promise<any>;
32
+ buildListQuery(args?: BuildListQueryArgsInterface): Promise<any>;
33
+ list(args?: ListArgsInterface): Promise<any>;
34
+ create(args: any): Promise<any[]>;
35
+ update(where: any, params: any): Promise<any>;
36
+ updateMany(params: any): Promise<any[]>;
37
+ increment(where: any, params: any): Promise<any>;
38
+ decrement(where: any, params: any): Promise<any>;
39
+ /**
40
+ * Inserts or updates data in the database.
41
+ * If the element of given array has not empty id field then the record is updated
42
+ * oterwise inserted
43
+ * @param params Array of objects to update or create
44
+ * @returns Array of updated or inserted objects
45
+ */
46
+ set(params: any): Promise<any[]>;
47
+ remove(where: any): Promise<any>;
48
+ }
49
+ export { BaseGateway };
@@ -0,0 +1,476 @@
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
+ import { v4 } from 'uuid';
11
+ import dayjs from 'dayjs';
12
+ import check from 'check-types';
13
+ import { camelCase, castArray, pullAll } from 'lodash';
14
+ import { arrToChunks, STATUSES, DateTimeHelpers, buildKey, Logger, LoggerLevels } from '@sdflc/utils';
15
+ import { DataCache } from './DataCache';
16
+ import { FIELDS, ID_FIELD } from './constants';
17
+ const DEFAULT_CHUNCK_SIZE = 2500;
18
+ class BaseGateway {
19
+ constructor(props) {
20
+ var _a, _b, _c;
21
+ this.dateTime = new DateTimeHelpers();
22
+ this.dateTimeNow = new Date();
23
+ this.config = props;
24
+ this.config.returnFields =
25
+ Array.isArray(this.config.returnFields) && this.config.returnFields.length > 0 ? this.config.returnFields : ['*'];
26
+ this.config.activeStatuses = Array.isArray(this.config.activeStatuses)
27
+ ? this.config.activeStatuses
28
+ : [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)) {
31
+ if (this.config.context.usedKeyPrefixes[this.config.keyPrefix]) {
32
+ 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
+ }
34
+ this.config.context.usedKeyPrefixes[this.config.keyPrefix] = true;
35
+ }
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);
38
+ }
39
+ getConfig() {
40
+ return this.config;
41
+ }
42
+ setConfigPart(props) {
43
+ Object.assign(this.config, props);
44
+ return this;
45
+ }
46
+ setLoader(loader) {
47
+ this.loader = loader;
48
+ return this;
49
+ }
50
+ setLoaderConfig(config) {
51
+ this.loader = new DataCache(Object.assign(Object.assign({}, this.config), config));
52
+ return this;
53
+ }
54
+ generateId(args) {
55
+ return __awaiter(this, void 0, void 0, function* () {
56
+ return v4();
57
+ });
58
+ }
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
+ });
89
+ }
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) {
107
+ 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
+ }
114
+ }
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]));
128
+ }
129
+ if (hasStatus === true) {
130
+ filtersAppliedQty++;
131
+ query.where(FIELDS.STATUS, '!=', STATUSES.REMOVED);
132
+ }
133
+ return filtersAppliedQty;
134
+ });
135
+ }
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
+ });
165
+ }
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
+ }
183
+ }
184
+ if (hasLang && localizationForField) {
185
+ params[this.getIdField()] = buildKey([params[camelCase(localizationForField)], params[camelCase(FIELDS.LANG)]]);
186
+ }
187
+ return params;
188
+ });
189
+ }
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
+ }
201
+ }
202
+ if (hasUserId) {
203
+ const userId = camelCase(FIELDS.USER_ID);
204
+ if (params[userId] === undefined) {
205
+ params[userId] = this.getContext().userId;
206
+ }
207
+ }
208
+ if (hasSpace) {
209
+ params[camelCase(FIELDS.SPACE_ID)] = this.getContext().spaceId;
210
+ }
211
+ if (hasUpdatedAt) {
212
+ params[camelCase(FIELDS.UPDATED_AT)] = this.dateTime.dbFormat(this.dateTimeNow);
213
+ }
214
+ if (hasUpdatedBy) {
215
+ const updatedBy = camelCase(FIELDS.UPDATED_BY);
216
+ if (params[updatedBy] === undefined) {
217
+ params[updatedBy] = this.getContext().userId;
218
+ }
219
+ }
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
+ }
228
+ }
229
+ if (hasLang && localizationForField) {
230
+ params[this.getIdField()] = buildKey([params[camelCase(localizationForField)], params[camelCase(FIELDS.LANG)]]);
231
+ }
232
+ return params;
233
+ });
234
+ }
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}')`);
257
+ }
258
+ return obj;
259
+ });
260
+ }
261
+ getRequestId() {
262
+ return this.config.context.requestId;
263
+ }
264
+ getContext() {
265
+ return this.config.context;
266
+ }
267
+ getGateways() {
268
+ return this.config.context.gateways || {};
269
+ }
270
+ getDb() {
271
+ return this.config.db;
272
+ }
273
+ getBuilder() {
274
+ var _a;
275
+ return (_a = this.getDb()) === null || _a === void 0 ? void 0 : _a.getBuilder(this.config.table);
276
+ }
277
+ getIdField() {
278
+ return this.config.idField || ID_FIELD;
279
+ }
280
+ getIdFieldUpdateRemove() {
281
+ return this.config.idFieldUpdateRemove || this.config.idField || ID_FIELD;
282
+ }
283
+ get(id) {
284
+ return __awaiter(this, void 0, void 0, function* () {
285
+ return this.loader.load(id);
286
+ });
287
+ }
288
+ getMany(ids) {
289
+ return __awaiter(this, void 0, void 0, function* () {
290
+ return this.loader.loadMany(ids);
291
+ });
292
+ }
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
+ });
300
+ }
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
+ });
322
+ }
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
+ });
344
+ }
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
+ });
359
+ }
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
+ });
376
+ }
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
+ });
391
+ }
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
+ });
406
+ }
407
+ /**
408
+ * Inserts or updates data in the database.
409
+ * If the element of given array has not empty id field then the record is updated
410
+ * oterwise inserted
411
+ * @param params Array of objects to update or create
412
+ * @returns Array of updated or inserted objects
413
+ */
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);
449
+ }
450
+ return result;
451
+ });
452
+ }
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
+ });
474
+ }
475
+ }
476
+ export { BaseGateway };
@@ -0,0 +1,14 @@
1
+ import { CacheInterface, LoaderInterface } from './interfaces';
2
+ declare class DataCache implements LoaderInterface {
3
+ private buildKey;
4
+ private loader;
5
+ private config;
6
+ private redisClient;
7
+ constructor(props: CacheInterface);
8
+ batchLoaderDefault(props: CacheInterface): (ids: any[]) => Promise<any[]>;
9
+ init(batchFunction: any, keyPrefix?: string, context?: any): void;
10
+ load(key: any): any;
11
+ loadMany(keys: any[]): any;
12
+ clear(key: any | any[]): void;
13
+ }
14
+ export { DataCache };
@@ -0,0 +1,98 @@
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
+ import DataLoader from 'dataloader';
11
+ import { RedisDataLoader } from './RedisDataLoader';
12
+ import { buildKey as defaultBuildKey } from '@sdflc/utils';
13
+ import { FIELDS } from '.';
14
+ import { castArray } from 'lodash';
15
+ class DataCache {
16
+ constructor(props) {
17
+ const { loaderFn, keyPrefix, context, buildKey, redisClient, table } = props || {};
18
+ if (!(props === null || props === void 0 ? void 0 : props.idField)) {
19
+ props.idField = FIELDS.ID;
20
+ }
21
+ if (!(props === null || props === void 0 ? void 0 : props.idFieldAs)) {
22
+ props.idFieldAs = FIELDS.ID;
23
+ }
24
+ this.config = props;
25
+ this.redisClient = redisClient;
26
+ this.buildKey = typeof buildKey === 'function' ? buildKey : defaultBuildKey;
27
+ this.batchLoaderDefault = this.batchLoaderDefault.bind(this);
28
+ const fn = typeof loaderFn === 'function' ? loaderFn : this.batchLoaderDefault(props);
29
+ const prefixToUse = (context === null || context === void 0 ? void 0 : context.keyPrefix) || keyPrefix || table;
30
+ this.init(fn, prefixToUse, context);
31
+ }
32
+ batchLoaderDefault(props) {
33
+ const { table, idField, idFieldAs, readAll, db } = props;
34
+ if (!table) {
35
+ throw Error(`DataCache requires 'table' property to be setup`);
36
+ }
37
+ else if (!idField && readAll == null) {
38
+ throw Error(`DataCache requires 'idField' or 'readAll' property to be setup`);
39
+ }
40
+ else if (!db) {
41
+ throw Error(`DataCache requires 'db' property to be setup`);
42
+ }
43
+ return (ids) => __awaiter(this, void 0, void 0, function* () {
44
+ const resultItems = [];
45
+ const readCfg = Object.assign(Object.assign({}, props), { buildKey: this.buildKey });
46
+ const idsToUse = castArray(ids);
47
+ if (!readAll) {
48
+ readCfg.mapBy = idFieldAs || idField;
49
+ readCfg.whereIn = {
50
+ field: idField,
51
+ values: idsToUse.filter((id) => id),
52
+ };
53
+ }
54
+ const dbItems = yield db.read(readCfg);
55
+ if (readAll) {
56
+ resultItems.push(...dbItems);
57
+ }
58
+ else {
59
+ resultItems.push(...idsToUse.map((id) => dbItems[this.buildKey(id)] || null));
60
+ }
61
+ return resultItems;
62
+ });
63
+ }
64
+ init(batchFunction, keyPrefix, context) {
65
+ if (this.redisClient) {
66
+ this.loader = new RedisDataLoader(this.redisClient,
67
+ // set a prefix for the keys stored in redis. This way you can avoid key
68
+ // collisions for different data-sets in your redis instance.
69
+ keyPrefix,
70
+ // create a regular loader. This should always be set with caching disabled.
71
+ {
72
+ load: (ids) => batchFunction(ids, context),
73
+ }, {
74
+ cache: true,
75
+ expire: this.config.cacheTtl,
76
+ });
77
+ }
78
+ else {
79
+ this.loader = new DataLoader((ids) => batchFunction(ids, context));
80
+ }
81
+ }
82
+ load(key) {
83
+ return this.loader.load(this.buildKey(key));
84
+ }
85
+ loadMany(keys) {
86
+ return this.loader.loadMany(keys.map((key) => this.buildKey(key)));
87
+ }
88
+ clear(key) {
89
+ var _a;
90
+ if (Array.isArray(key)) {
91
+ key.forEach((item) => { var _a; return (_a = this.loader) === null || _a === void 0 ? void 0 : _a.clear(this.buildKey(item)); });
92
+ }
93
+ else {
94
+ (_a = this.loader) === null || _a === void 0 ? void 0 : _a.clear(this.buildKey(key));
95
+ }
96
+ }
97
+ }
98
+ export { DataCache };
@@ -0,0 +1,32 @@
1
+ import { DatabaseOptions, DatabaseReadInterface } from './interfaces';
2
+ declare class Database {
3
+ private trx;
4
+ private knexHandle;
5
+ private dbSchema;
6
+ private logger;
7
+ constructor(props: DatabaseOptions);
8
+ destroy(): void;
9
+ isDbError(ex: any): any[];
10
+ createTransaction(trx: any): Promise<unknown>;
11
+ getSchema(): string;
12
+ getBuilder(arg: any): any;
13
+ raw(query: string, bindings?: any): any;
14
+ runRawQuery(query: string, bindings: any): Promise<any>;
15
+ startTransaction(): Promise<unknown>;
16
+ setTransaction(trx: any): void;
17
+ commitTransaction(): Promise<void>;
18
+ rollbackTransaction(): Promise<void>;
19
+ doCalculated(item: any, calculatedFields: any[]): void;
20
+ read(args: DatabaseReadInterface): Promise<any>;
21
+ createSortBy(sortBy: any[], defaultSortBy?: any): any[] | null;
22
+ createLimitOffset(page: number, pageSize: number): {
23
+ limit: number | undefined;
24
+ offset: number;
25
+ };
26
+ createLimitOffsetSortBy(pagination: any, defaultSortBy: any): {
27
+ limit: number | undefined;
28
+ offset: number;
29
+ sortBy: any[] | null;
30
+ };
31
+ }
32
+ export { Database };