@sdflc/backend-helpers 1.0.26 → 1.0.29

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 (39) hide show
  1. package/README.md +1 -1
  2. package/build/{baseController.d.ts → BaseController.d.ts} +0 -0
  3. package/build/{baseController.js → BaseController.js} +0 -0
  4. package/build/{baseCore.d.ts → BaseCore.d.ts} +13 -19
  5. package/build/{baseCore.js → BaseCore.js} +114 -156
  6. package/build/{baseGateway.d.ts → BaseGateway.d.ts} +14 -11
  7. package/build/{baseGateway.js → BaseGateway.js} +134 -95
  8. package/build/{dataCache.d.ts → DataCache.d.ts} +0 -0
  9. package/build/{dataCache.js → DataCache.js} +2 -2
  10. package/build/{database.d.ts → Database.d.ts} +0 -0
  11. package/build/{database.js → Database.js} +0 -0
  12. package/build/{dbMigratorAndSeeder.d.ts → DbMigratorAndSeeder.d.ts} +0 -0
  13. package/build/{dbMigratorAndSeeder.js → DbMigratorAndSeeder.js} +0 -0
  14. package/build/apiContext.d.ts +3 -3
  15. package/build/apiContext.js +89 -32
  16. package/build/constants.d.ts +4 -5
  17. package/build/constants.js +18 -4
  18. package/build/dbTableHelpers.js +29 -33
  19. package/build/index.d.ts +8 -10
  20. package/build/index.js +17 -20
  21. package/build/interfaces/ApiContext.d.ts +23 -0
  22. package/build/interfaces/{BaseCoreInterface.js → ApiContext.js} +0 -0
  23. package/build/interfaces/ApiContextInterface.d.ts +5 -1
  24. package/build/interfaces/BaseCorePropsInterface.d.ts +31 -0
  25. package/build/interfaces/{BaseGatewayInterface.js → BaseCorePropsInterface.js} +0 -0
  26. package/build/interfaces/BaseGatewayPropsInterface.d.ts +29 -0
  27. package/build/interfaces/BaseGatewayPropsInterface.js +2 -0
  28. package/build/interfaces/CacheInterface.d.ts +3 -3
  29. package/build/interfaces/CoreActionInterface.d.ts +1 -1
  30. package/build/interfaces/JwtTokenSecretAndSettings.d.ts +5 -0
  31. package/build/interfaces/JwtTokenSecretAndSettings.js +2 -0
  32. package/build/interfaces/index.d.ts +4 -2
  33. package/build/resolversHelpers.js +11 -10
  34. package/build/userToken.js +3 -3
  35. package/package.json +2 -2
  36. package/build/baseGatewayHelpers.d.ts +0 -20
  37. package/build/baseGatewayHelpers.js +0 -87
  38. package/build/interfaces/BaseCoreInterface.d.ts +0 -43
  39. package/build/interfaces/BaseGatewayInterface.d.ts +0 -27
@@ -1,23 +1,26 @@
1
- import { BaseGatewayInterface, ListArgsInterface } from './interfaces';
2
- import { BaseCore } from './baseCore';
1
+ import { DateTimeHelpers } from '@sdflc/utils';
2
+ import { ApiContext, BaseGatewayPropsInterface, ListArgsInterface } from './interfaces';
3
+ import { Database } from './Database';
3
4
  declare class BaseGateway {
4
- protected config: BaseGatewayInterface;
5
+ protected config: BaseGatewayPropsInterface;
5
6
  protected loader: any;
6
- protected insertChunkSize: number;
7
- protected returnFields: any[];
8
- constructor(props: BaseGatewayInterface);
9
- generateId(args?: any): Promise<any>;
7
+ protected dateTime: DateTimeHelpers;
8
+ protected dateTimeNow: Date;
9
+ constructor(props: BaseGatewayPropsInterface);
10
+ setConfigPart(props: BaseGatewayPropsInterface): this;
11
+ generateId(args?: any): Promise<string>;
10
12
  onListFilter(query: any, filterParams: any): Promise<void>;
11
13
  onUpdateFilter(query: any, filterParams: any): Promise<void>;
12
14
  onRemoveFilter(query: any, filterParams: any): Promise<void>;
13
15
  transformOnCreate(args: any): Promise<any>;
14
16
  transformOnUpdate(params: any, where?: any): Promise<any>;
15
17
  transformOnRemove(args?: any): Promise<any>;
16
- getDb(): import("./database").Database;
18
+ getRequestId(): string;
19
+ getContext(): ApiContext;
20
+ getGateways(): any;
21
+ getDb(): Database;
17
22
  getBuilder(): any;
18
- getIdField(): any;
19
- getCore(): BaseCore | undefined;
20
- setCore(core: BaseCore): void;
23
+ getIdField(): string;
21
24
  get(id: any): Promise<any>;
22
25
  getMany(ids: any[]): Promise<any>;
23
26
  list(args?: ListArgsInterface): Promise<any>;
@@ -51,139 +51,177 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
51
51
  };
52
52
  Object.defineProperty(exports, "__esModule", { value: true });
53
53
  exports.BaseGateway = void 0;
54
+ var uuid_1 = require("uuid");
55
+ var dayjs_1 = __importDefault(require("dayjs"));
54
56
  var lodash_1 = require("lodash");
55
57
  var utils_1 = require("@sdflc/utils");
56
- var dataCache_1 = require("./dataCache");
57
- var constants_1 = __importDefault(require("./constants"));
58
- var ID_FIELD = constants_1.default.ID_FIELD;
59
- var defaultUpdateRemoveFilter = function (config) { return function (query, params) {
60
- var idName = config.idField || ID_FIELD;
61
- query.where(idName, params[idName]);
62
- }; };
58
+ var DataCache_1 = require("./DataCache");
59
+ var constants_1 = require("./constants");
60
+ var DEFAULT_CHUNCK_SIZE = 2500;
63
61
  var BaseGateway = /** @class */ (function () {
64
62
  function BaseGateway(props) {
65
- var _a;
63
+ this.dateTime = new utils_1.DateTimeHelpers();
64
+ this.dateTimeNow = new Date();
66
65
  this.config = props;
67
- this.insertChunkSize = (_a = props === null || props === void 0 ? void 0 : props.insertChunkSize) !== null && _a !== void 0 ? _a : 2500;
68
- this.returnFields =
69
- Array.isArray(this.config.returnFields) && this.config.returnFields.length > 0
70
- ? this.config.returnFields
71
- : [this.getIdField()];
72
- this.loader = typeof this.config.loader === 'function' ? this.config.loader : new dataCache_1.DataCache(this.config);
66
+ this.config.returnFields =
67
+ Array.isArray(this.config.returnFields) && this.config.returnFields.length > 0 ? this.config.returnFields : ['*'];
68
+ this.loader = typeof this.config.loader === 'function' ? this.config.loader : new DataCache_1.DataCache(this.config);
73
69
  }
70
+ BaseGateway.prototype.setConfigPart = function (props) {
71
+ Object.assign(this.config, props);
72
+ return this;
73
+ };
74
74
  BaseGateway.prototype.generateId = function (args) {
75
75
  return __awaiter(this, void 0, void 0, function () {
76
76
  return __generator(this, function (_a) {
77
- return [2 /*return*/, typeof this.config.idGenerator === 'function' ? this.config.idGenerator(args) : undefined];
77
+ return [2 /*return*/, (0, uuid_1.v4)()];
78
78
  });
79
79
  });
80
80
  };
81
81
  BaseGateway.prototype.onListFilter = function (query, filterParams) {
82
82
  return __awaiter(this, void 0, void 0, function () {
83
- return __generator(this, function (_a) {
84
- switch (_a.label) {
85
- case 0:
86
- if (!(typeof this.config.filter === 'function')) return [3 /*break*/, 2];
87
- return [4 /*yield*/, this.config.filter(query, filterParams)];
88
- case 1:
89
- _a.sent();
90
- _a.label = 2;
91
- case 2: return [2 /*return*/];
83
+ var _a, hasStatus, hasRemovedAt, hasSpace, activeStatuses, hasLang, fieldForKeyword;
84
+ var _b;
85
+ return __generator(this, function (_c) {
86
+ _a = this.config || {}, hasStatus = _a.hasStatus, hasRemovedAt = _a.hasRemovedAt, hasSpace = _a.hasSpace, activeStatuses = _a.activeStatuses, hasLang = _a.hasLang, fieldForKeyword = _a.fieldForKeyword;
87
+ // This function should be overriden
88
+ if (hasStatus) {
89
+ query.whereIn(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));
90
+ }
91
+ if (hasRemovedAt) {
92
+ query.whereNull(constants_1.FIELDS.REMOVED_AT);
93
+ }
94
+ if (hasSpace) {
95
+ query.where((_b = {}, _b[constants_1.FIELDS.SPACE_ID] = filterParams === null || filterParams === void 0 ? void 0 : filterParams[constants_1.FIELDS.SPACE_ID], _b));
96
+ }
97
+ if (hasLang && (filterParams === null || filterParams === void 0 ? void 0 : filterParams[constants_1.FIELDS.LANG])) {
98
+ query.whereIn(constants_1.FIELDS.LANG, (0, lodash_1.castArray)(filterParams === null || filterParams === void 0 ? void 0 : filterParams[constants_1.FIELDS.LANG]));
92
99
  }
100
+ if (filterParams === null || filterParams === void 0 ? void 0 : filterParams[this.getIdField()]) {
101
+ query.whereIn(constants_1.FIELDS.ID, (0, lodash_1.castArray)(filterParams === null || filterParams === void 0 ? void 0 : filterParams[this.getIdField()]));
102
+ }
103
+ if (fieldForKeyword && filterParams.keyword) {
104
+ query.whereRaw("".concat(fieldForKeyword, " ILIKE ?"), "%".concat(filterParams.keyword, "%"));
105
+ }
106
+ return [2 /*return*/];
93
107
  });
94
108
  });
95
109
  };
96
110
  BaseGateway.prototype.onUpdateFilter = function (query, filterParams) {
97
111
  return __awaiter(this, void 0, void 0, function () {
98
- return __generator(this, function (_a) {
99
- switch (_a.label) {
100
- case 0:
101
- if (!(typeof this.config.updateFilter === 'function')) return [3 /*break*/, 2];
102
- return [4 /*yield*/, this.config.updateFilter(query, filterParams)];
103
- case 1:
104
- _a.sent();
105
- return [3 /*break*/, 4];
106
- case 2: return [4 /*yield*/, defaultUpdateRemoveFilter(this.config)(query, filterParams)];
107
- case 3:
108
- _a.sent();
109
- _a.label = 4;
110
- case 4: return [2 /*return*/];
112
+ var _a, hasStatus, hasVersion, idName;
113
+ return __generator(this, function (_b) {
114
+ _a = this.config, hasStatus = _a.hasStatus, hasVersion = _a.hasVersion;
115
+ idName = this.getIdField();
116
+ if (filterParams[idName]) {
117
+ query.where(idName, filterParams[idName]);
118
+ }
119
+ if (hasVersion && filterParams[constants_1.FIELDS.VERSION]) {
120
+ query.where(constants_1.FIELDS.VERSION, filterParams[constants_1.FIELDS.VERSION]);
111
121
  }
122
+ if (hasStatus) {
123
+ if (Array.isArray(filterParams === null || filterParams === void 0 ? void 0 : filterParams[constants_1.FIELDS.STATUS])) {
124
+ query.whereIn(constants_1.FIELDS.STATUS, filterParams === null || filterParams === void 0 ? void 0 : filterParams[constants_1.FIELDS.STATUS]);
125
+ }
126
+ else {
127
+ query.where(constants_1.FIELDS.STATUS, '!=', utils_1.STATUSES.REMOVED);
128
+ }
129
+ }
130
+ return [2 /*return*/];
112
131
  });
113
132
  });
114
133
  };
115
134
  BaseGateway.prototype.onRemoveFilter = function (query, filterParams) {
116
135
  return __awaiter(this, void 0, void 0, function () {
136
+ var hasStatus, arr;
117
137
  return __generator(this, function (_a) {
118
- switch (_a.label) {
119
- case 0:
120
- if (!(typeof this.config.removeFilter === 'function')) return [3 /*break*/, 2];
121
- return [4 /*yield*/, this.config.removeFilter(query, filterParams)];
122
- case 1:
123
- _a.sent();
124
- return [3 /*break*/, 4];
125
- case 2: return [4 /*yield*/, defaultUpdateRemoveFilter(this.config)(query, filterParams)];
126
- case 3:
127
- _a.sent();
128
- _a.label = 4;
129
- case 4: return [2 /*return*/];
138
+ hasStatus = this.config.hasStatus;
139
+ arr = (0, lodash_1.castArray)(filterParams);
140
+ query = query.whereIn(constants_1.FIELDS.ID, arr.map(function (item) { return item[constants_1.FIELDS.ID]; }));
141
+ if (hasStatus === true) {
142
+ query.where(constants_1.FIELDS.STATUS, '!=', utils_1.STATUSES.REMOVED);
130
143
  }
144
+ return [2 /*return*/];
131
145
  });
132
146
  });
133
147
  };
134
148
  BaseGateway.prototype.transformOnCreate = function (args) {
135
149
  return __awaiter(this, void 0, void 0, function () {
136
- return __generator(this, function (_a) {
137
- switch (_a.label) {
138
- case 0:
139
- if (!(typeof this.config.insertFormatter === 'function')) return [3 /*break*/, 2];
140
- return [4 /*yield*/, this.config.insertFormatter(args)];
141
- case 1: return [2 /*return*/, _a.sent()];
142
- case 2: return [2 /*return*/, args];
150
+ var _a, hasCreatedAt, hasCreatedBy;
151
+ return __generator(this, function (_b) {
152
+ _a = this.config, hasCreatedAt = _a.hasCreatedAt, hasCreatedBy = _a.hasCreatedBy;
153
+ if (hasCreatedAt) {
154
+ args[constants_1.FIELDS.CREATED_AT] = this.dateTime.dbFormat(this.dateTimeNow);
143
155
  }
156
+ if (hasCreatedBy) {
157
+ if (args[constants_1.FIELDS.CREATED_BY] === undefined) {
158
+ args[constants_1.FIELDS.CREATED_BY] = this.getContext().userId;
159
+ }
160
+ }
161
+ return [2 /*return*/, args];
144
162
  });
145
163
  });
146
164
  };
147
165
  BaseGateway.prototype.transformOnUpdate = function (params, where) {
148
166
  return __awaiter(this, void 0, void 0, function () {
149
- return __generator(this, function (_a) {
150
- switch (_a.label) {
151
- case 0:
152
- if (!(typeof this.config.updateFormatter === 'function')) return [3 /*break*/, 2];
153
- return [4 /*yield*/, this.config.updateFormatter(params, where)];
154
- case 1: return [2 /*return*/, _a.sent()];
155
- case 2: return [2 /*return*/, params];
167
+ var _a, hasUpdatedAt, hasUpdatedBy;
168
+ return __generator(this, function (_b) {
169
+ _a = this.config, hasUpdatedAt = _a.hasUpdatedAt, hasUpdatedBy = _a.hasUpdatedBy;
170
+ if (hasUpdatedAt) {
171
+ params[constants_1.FIELDS.UPDATED_AT] = this.dateTime.dbFormat(this.dateTimeNow);
172
+ }
173
+ if (hasUpdatedBy) {
174
+ if (params[constants_1.FIELDS.UPDATED_BY] === undefined) {
175
+ params[constants_1.FIELDS.UPDATED_BY] = this.getContext().userId;
176
+ }
156
177
  }
178
+ return [2 /*return*/, params];
157
179
  });
158
180
  });
159
181
  };
160
182
  BaseGateway.prototype.transformOnRemove = function (args) {
161
183
  return __awaiter(this, void 0, void 0, function () {
162
- return __generator(this, function (_a) {
163
- switch (_a.label) {
164
- case 0:
165
- if (!(typeof this.config.removeFormatter === 'function')) return [3 /*break*/, 2];
166
- return [4 /*yield*/, this.config.removeFormatter(args)];
167
- case 1: return [2 /*return*/, _a.sent()];
168
- case 2: return [2 /*return*/, args];
184
+ var _a, hasRemovedAt, hasRemovedAtStr, hasStatus, hasRemovedBy, removalTime, obj;
185
+ return __generator(this, function (_b) {
186
+ _a = this.config, hasRemovedAt = _a.hasRemovedAt, hasRemovedAtStr = _a.hasRemovedAtStr, hasStatus = _a.hasStatus, hasRemovedBy = _a.hasRemovedBy;
187
+ removalTime = (0, dayjs_1.default)();
188
+ obj = __assign({}, args);
189
+ if (hasRemovedAt) {
190
+ obj[constants_1.FIELDS.REMOVED_AT] = removalTime.toDate();
191
+ }
192
+ if (hasRemovedAtStr === true) {
193
+ obj[constants_1.FIELDS.REMOVED_AT_STR] = removalTime.format('YYYYMMDDTHHmmssZ');
169
194
  }
195
+ if (hasStatus === true) {
196
+ obj[constants_1.FIELDS.STATUS] = utils_1.STATUSES.REMOVED;
197
+ }
198
+ if (hasRemovedBy) {
199
+ if (args[constants_1.FIELDS.REMOVED_BY] === undefined) {
200
+ args[constants_1.FIELDS.REMOVED_BY] = this.getContext().userId;
201
+ }
202
+ }
203
+ return [2 /*return*/, obj];
170
204
  });
171
205
  });
172
206
  };
207
+ BaseGateway.prototype.getRequestId = function () {
208
+ return this.config.context.requestId;
209
+ };
210
+ BaseGateway.prototype.getContext = function () {
211
+ return this.config.context;
212
+ };
213
+ BaseGateway.prototype.getGateways = function () {
214
+ return this.config.context.gateways || {};
215
+ };
173
216
  BaseGateway.prototype.getDb = function () {
174
217
  return this.config.db;
175
218
  };
176
219
  BaseGateway.prototype.getBuilder = function () {
177
- return this.getDb().getBuilder(this.config.table);
220
+ var _a;
221
+ return (_a = this.getDb()) === null || _a === void 0 ? void 0 : _a.getBuilder(this.config.table);
178
222
  };
179
223
  BaseGateway.prototype.getIdField = function () {
180
- return this.config.idField || ID_FIELD;
181
- };
182
- BaseGateway.prototype.getCore = function () {
183
- return this.config.core;
184
- };
185
- BaseGateway.prototype.setCore = function (core) {
186
- this.config.core = core;
224
+ return this.config.idField || constants_1.ID_FIELD;
187
225
  };
188
226
  BaseGateway.prototype.get = function (id) {
189
227
  return __awaiter(this, void 0, void 0, function () {
@@ -240,43 +278,44 @@ var BaseGateway = /** @class */ (function () {
240
278
  });
241
279
  };
242
280
  BaseGateway.prototype.create = function (args) {
281
+ var _a;
243
282
  return __awaiter(this, void 0, void 0, function () {
244
283
  var objects, idx, len, arg, id, obj, result, chunks, idx, len, items;
245
- return __generator(this, function (_a) {
246
- switch (_a.label) {
284
+ return __generator(this, function (_b) {
285
+ switch (_b.label) {
247
286
  case 0:
248
287
  objects = (0, lodash_1.castArray)(args);
249
288
  if (!args || objects.length === 0) {
250
289
  return [2 /*return*/, []];
251
290
  }
252
291
  idx = 0, len = args.length;
253
- _a.label = 1;
292
+ _b.label = 1;
254
293
  case 1:
255
294
  if (!(idx < len)) return [3 /*break*/, 5];
256
295
  arg = args[idx];
257
296
  return [4 /*yield*/, this.generateId(arg)];
258
297
  case 2:
259
- id = _a.sent();
298
+ id = _b.sent();
260
299
  return [4 /*yield*/, this.transformOnCreate(__assign({ id: id }, arg))];
261
300
  case 3:
262
- obj = _a.sent();
301
+ obj = _b.sent();
263
302
  objects.push(obj);
264
- _a.label = 4;
303
+ _b.label = 4;
265
304
  case 4:
266
305
  ++idx;
267
306
  return [3 /*break*/, 1];
268
307
  case 5:
269
308
  result = [];
270
- chunks = (0, utils_1.arrToChunks)(objects, this.insertChunkSize);
309
+ chunks = (0, utils_1.arrToChunks)(objects, ((_a = this.config) === null || _a === void 0 ? void 0 : _a.insertChunkSize) || DEFAULT_CHUNCK_SIZE);
271
310
  idx = 0, len = chunks.length;
272
- _a.label = 6;
311
+ _b.label = 6;
273
312
  case 6:
274
313
  if (!(idx < len)) return [3 /*break*/, 9];
275
- return [4 /*yield*/, this.getBuilder().insert(chunks[idx]).returning(this.returnFields)];
314
+ return [4 /*yield*/, this.getBuilder().insert(chunks[idx]).returning(this.config.returnFields)];
276
315
  case 7:
277
- items = _a.sent();
316
+ items = _b.sent();
278
317
  result.push.apply(result, items);
279
- _a.label = 8;
318
+ _b.label = 8;
280
319
  case 8:
281
320
  ++idx;
282
321
  return [3 /*break*/, 6];
@@ -294,7 +333,7 @@ var BaseGateway = /** @class */ (function () {
294
333
  case 0: return [4 /*yield*/, this.transformOnUpdate(params, where)];
295
334
  case 1:
296
335
  object = _a.sent();
297
- query = this.getBuilder().update(object).returning(this.returnFields);
336
+ query = this.getBuilder().update(object).returning(this.config.returnFields);
298
337
  return [4 /*yield*/, this.onUpdateFilter(query, where)];
299
338
  case 2:
300
339
  _a.sent();
@@ -351,7 +390,7 @@ var BaseGateway = /** @class */ (function () {
351
390
  case 0: return [4 /*yield*/, this.transformOnUpdate(params, where)];
352
391
  case 1:
353
392
  object = _a.sent();
354
- query = this.getBuilder().increment(object).returning(this.returnFields);
393
+ query = this.getBuilder().increment(object).returning(this.config.returnFields);
355
394
  return [4 /*yield*/, this.onUpdateFilter(query, where)];
356
395
  case 2:
357
396
  _a.sent();
@@ -375,7 +414,7 @@ var BaseGateway = /** @class */ (function () {
375
414
  case 0: return [4 /*yield*/, this.transformOnUpdate(params, where)];
376
415
  case 1:
377
416
  object = _a.sent();
378
- query = this.getBuilder().decrement(object).returning(this.returnFields);
417
+ query = this.getBuilder().decrement(object).returning(this.config.returnFields);
379
418
  return [4 /*yield*/, this.onUpdateFilter(query, where)];
380
419
  case 2:
381
420
  _a.sent();
@@ -407,7 +446,7 @@ var BaseGateway = /** @class */ (function () {
407
446
  idField = this.getIdField();
408
447
  return [4 /*yield*/, this.getBuilder()
409
448
  .insert((0, lodash_1.castArray)(params))
410
- .returning(this.returnFields)
449
+ .returning(this.config.returnFields)
411
450
  .onConflict(this.config.setFields || idField)
412
451
  .merge()];
413
452
  case 1:
@@ -428,13 +467,13 @@ var BaseGateway = /** @class */ (function () {
428
467
  case 0:
429
468
  query = this.getBuilder();
430
469
  if (!hardRemove) return [3 /*break*/, 1];
431
- query.delete(this.returnFields);
470
+ query.delete(this.config.returnFields);
432
471
  return [3 /*break*/, 3];
433
472
  case 1:
434
473
  _b = (_a = query).update;
435
474
  return [4 /*yield*/, this.transformOnRemove()];
436
475
  case 2:
437
- _b.apply(_a, [_c.sent()]).returning(this.returnFields);
476
+ _b.apply(_a, [_c.sent()]).returning(this.config.returnFields);
438
477
  _c.label = 3;
439
478
  case 3: return [4 /*yield*/, this.onRemoveFilter(query, where)];
440
479
  case 4:
File without changes
@@ -56,13 +56,13 @@ var redis_dataloader_1 = __importDefault(require("redis-dataloader"));
56
56
  var utils_1 = require("@sdflc/utils");
57
57
  var DataCache = /** @class */ (function () {
58
58
  function DataCache(props) {
59
- var _a = props || {}, loaderFn = _a.loaderFn, keyPrefix = _a.keyPrefix, context = _a.context, buildKey = _a.buildKey, redisClient = _a.redisClient;
59
+ var _a = props || {}, loaderFn = _a.loaderFn, keyPrefix = _a.keyPrefix, context = _a.context, buildKey = _a.buildKey, redisClient = _a.redisClient, table = _a.table;
60
60
  this.config = props;
61
61
  this.buildKey = typeof buildKey === 'function' ? buildKey : utils_1.buildKey;
62
62
  this.batchLoaderDefault = this.batchLoaderDefault.bind(this);
63
63
  this.redisDataLoader = redisClient ? (0, redis_dataloader_1.default)({ redis: redisClient }) : null;
64
64
  var fn = typeof loaderFn === 'function' ? loaderFn : this.batchLoaderDefault(props);
65
- var prefixToUse = (context === null || context === void 0 ? void 0 : context.keyPrefix) || keyPrefix;
65
+ var prefixToUse = (context === null || context === void 0 ? void 0 : context.keyPrefix) || keyPrefix || table;
66
66
  this.init(fn, prefixToUse, context);
67
67
  }
68
68
  DataCache.prototype.batchLoaderDefault = function (props) {
File without changes
File without changes
@@ -1,11 +1,11 @@
1
- import { ApiContextInterface } from './interfaces';
1
+ import { ApiContext, ApiContextInterface } from './interfaces';
2
2
  /**
3
3
  * Creates a GraphQL context object with all available cores.
4
4
  * @returns {object} A context object with all available cores
5
5
  */
6
- export declare const createApiContext: (args: ApiContextInterface) => Promise<any>;
6
+ export declare const createApiContext: (args: ApiContextInterface) => Promise<ApiContext>;
7
7
  /**
8
8
  * Creates default a GraphQL context object with all avilable cores.
9
9
  * @returns {object} A context object with all available cores
10
10
  */
11
- export declare const createContextDefault: (args: any) => Promise<any>;
11
+ export declare const createContextDefault: (args: any) => Promise<ApiContext>;
@@ -51,40 +51,59 @@ exports.createContextDefault = exports.createApiContext = void 0;
51
51
  var lodash_1 = require("lodash");
52
52
  var uuid_1 = require("uuid");
53
53
  var utils_1 = require("@sdflc/utils");
54
- var database_1 = require("./database");
54
+ var Database_1 = require("./Database");
55
+ var constants_1 = require("./constants");
55
56
  /**
56
57
  * Creates a GraphQL context object with all available cores.
57
58
  * @returns {object} A context object with all available cores
58
59
  */
59
60
  var createApiContext = function (args) { return __awaiter(void 0, void 0, void 0, function () {
60
- var _a, cores, req, getCoreContext, extendContext, inRequestId, keys, requestId, coreContext, _b, context;
61
- return __generator(this, function (_c) {
62
- switch (_c.label) {
61
+ var _a, cores, gateways, req, getCoreContext, getGatewayContext, extendContext, inRequestId, requestId, coreContext, _b, gatewayContext, _c, context;
62
+ return __generator(this, function (_d) {
63
+ switch (_d.label) {
63
64
  case 0:
64
- _a = args || {}, cores = _a.cores, req = _a.req, getCoreContext = _a.getCoreContext, extendContext = _a.extendContext, inRequestId = _a.requestId;
65
- keys = Object.keys(cores || {});
65
+ _a = args || {}, cores = _a.cores, gateways = _a.gateways, req = _a.req, getCoreContext = _a.getCoreContext, getGatewayContext = _a.getGatewayContext, extendContext = _a.extendContext, inRequestId = _a.requestId;
66
66
  requestId = inRequestId || (0, uuid_1.v4)();
67
67
  if (!(typeof getCoreContext === 'function')) return [3 /*break*/, 2];
68
68
  return [4 /*yield*/, getCoreContext({ req: req })];
69
69
  case 1:
70
- _b = _c.sent();
70
+ _b = _d.sent();
71
71
  return [3 /*break*/, 3];
72
72
  case 2:
73
73
  _b = {};
74
- _c.label = 3;
74
+ _d.label = 3;
75
75
  case 3:
76
76
  coreContext = _b;
77
- context = keys.reduce(function (acc, key) {
78
- acc[(0, lodash_1.camelCase)(key)] = new cores[key](__assign(__assign({}, coreContext), { requestId: requestId }));
77
+ if (!(typeof getGatewayContext === 'function')) return [3 /*break*/, 5];
78
+ return [4 /*yield*/, getGatewayContext({ req: req })];
79
+ case 4:
80
+ _c = _d.sent();
81
+ return [3 /*break*/, 6];
82
+ case 5:
83
+ _c = {};
84
+ _d.label = 6;
85
+ case 6:
86
+ gatewayContext = _c;
87
+ context = {
88
+ requestId: requestId,
89
+ cores: {},
90
+ gateways: {},
91
+ req: req,
92
+ };
93
+ context.cores = Object.keys(cores || {}).reduce(function (acc, key) {
94
+ acc[(0, lodash_1.camelCase)(key)] = new cores[key](__assign(__assign({}, coreContext), { context: context }));
95
+ return acc;
96
+ }, {});
97
+ context.gateways = Object.keys(gateways || {}).reduce(function (acc, key) {
98
+ acc[(0, lodash_1.camelCase)(key)] = new gateways[key](__assign(__assign({}, gatewayContext), { context: context }));
79
99
  return acc;
80
100
  }, {});
81
- context.requestId = requestId;
82
- if (!(typeof extendContext === 'function')) return [3 /*break*/, 5];
101
+ if (!(typeof extendContext === 'function')) return [3 /*break*/, 8];
83
102
  return [4 /*yield*/, extendContext({ context: context, req: req })];
84
- case 4:
85
- _c.sent();
86
- _c.label = 5;
87
- case 5: return [2 /*return*/, context];
103
+ case 7:
104
+ _d.sent();
105
+ _d.label = 8;
106
+ case 8: return [2 /*return*/, context];
88
107
  }
89
108
  });
90
109
  }); };
@@ -94,31 +113,49 @@ exports.createApiContext = createApiContext;
94
113
  * @returns {object} A context object with all available cores
95
114
  */
96
115
  var createContextDefault = function (args) { return __awaiter(void 0, void 0, void 0, function () {
97
- var _a, knexConfig, dbSchema, cores, req, extendContext, getCoreContext, authorization, spaceId, apiKey, managementApiKey, accountId, roleId, userId, userAgent, referer, ipAddress, acceptLanguage, languages, requestedLang, requestId, db;
116
+ var _a, knexConfig, isProduction, logger, doAuth, spaceGw, interserviceApiKey, jwtSecret, verifyTokenArgs, dbSchema, cores, gateways, req, extendContext, getCoreContext, getGatewayContext, authorization, spaceId, apiKey, managementApiKey, accountId, roleId, userId, userAgent, referer, ipAddress, acceptLanguage, languages, requestedLang, requestId, db, sharedContext;
98
117
  return __generator(this, function (_b) {
99
118
  switch (_b.label) {
100
119
  case 0:
101
- _a = args || {}, knexConfig = _a.knexConfig, dbSchema = _a.dbSchema, cores = _a.cores, req = _a.req, extendContext = _a.extendContext, getCoreContext = _a.getCoreContext;
102
- authorization = req.headers['authorization'] ? req.headers['authorization'].replace('Bearer ', '') : undefined;
103
- spaceId = req.headers['x-space-id'];
104
- apiKey = req.headers['x-api-key'];
105
- managementApiKey = req.headers['x-management-api-key'];
106
- accountId = req.headers['x-account-id'];
107
- roleId = req.headers['x-role-id'];
108
- userId = req.headers['x-user-id'];
109
- userAgent = req.headers['user-agent'];
110
- referer = req.headers['referer'];
111
- ipAddress = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
112
- acceptLanguage = req.headers['accept-language'];
120
+ _a = args || {}, knexConfig = _a.knexConfig, isProduction = _a.isProduction, logger = _a.logger, doAuth = _a.doAuth, spaceGw = _a.spaceGw, interserviceApiKey = _a.interserviceApiKey, jwtSecret = _a.jwtSecret, verifyTokenArgs = _a.verifyTokenArgs, dbSchema = _a.dbSchema, cores = _a.cores, gateways = _a.gateways, req = _a.req, extendContext = _a.extendContext, getCoreContext = _a.getCoreContext, getGatewayContext = _a.getGatewayContext;
121
+ authorization = req.headers[constants_1.HEADERS.AUTHORIZATION]
122
+ ? req.headers[constants_1.HEADERS.AUTHORIZATION].replace('Bearer ', '')
123
+ : undefined;
124
+ spaceId = req.headers[constants_1.HEADERS.SPACE_ID];
125
+ apiKey = req.headers[constants_1.HEADERS.API_KEY];
126
+ managementApiKey = req.headers[constants_1.HEADERS.MANAGEMENT_API_KEY];
127
+ accountId = req.headers[constants_1.HEADERS.ACCOUNT_ID];
128
+ roleId = req.headers[constants_1.HEADERS.ROLE_ID];
129
+ userId = req.headers[constants_1.HEADERS.USER_ID];
130
+ userAgent = req.headers[constants_1.HEADERS.USER_AGENT];
131
+ referer = req.headers[constants_1.HEADERS.REFERER];
132
+ ipAddress = req.headers[constants_1.HEADERS.IP_ADDRESS] || req.connection.remoteAddress;
133
+ acceptLanguage = req.headers[constants_1.HEADERS.ACCEPT_LANGUAGE];
113
134
  languages = (0, utils_1.extractLanguages)(acceptLanguage);
114
- requestedLang = req.query['lang'];
135
+ requestedLang = req.headers[constants_1.HEADERS.ACCEPT_LANGUAGE] || req.query[constants_1.HEADERS.ACCEPT_LANGUAGE];
115
136
  requestId = (0, uuid_1.v4)();
116
- db = new database_1.Database({
137
+ db = new Database_1.Database({
117
138
  knexConfig: knexConfig,
118
139
  dbSchema: dbSchema,
119
140
  });
141
+ sharedContext = {
142
+ spaceId: spaceId,
143
+ apiKey: apiKey,
144
+ managementApiKey: managementApiKey,
145
+ userAgent: userAgent,
146
+ referer: referer,
147
+ ipAddress: ipAddress,
148
+ acceptLanguage: acceptLanguage,
149
+ languages: languages,
150
+ requestedLang: requestedLang,
151
+ authorization: authorization,
152
+ accountId: accountId,
153
+ roleId: roleId,
154
+ userId: userId,
155
+ };
120
156
  return [4 /*yield*/, (0, exports.createApiContext)({
121
157
  cores: cores,
158
+ gateways: gateways,
122
159
  req: req,
123
160
  requestId: requestId,
124
161
  extendContext: function (_a) {
@@ -139,7 +176,27 @@ var createContextDefault = function (args) { return __awaiter(void 0, void 0, vo
139
176
  case 1:
140
177
  extendCoreConext = _a.sent();
141
178
  _a.label = 2;
142
- case 2: return [2 /*return*/, __assign(__assign({ db: db }, extendCoreConext), { context: __assign({ spaceId: spaceId, apiKey: apiKey, managementApiKey: managementApiKey, userAgent: userAgent, referer: referer, ipAddress: ipAddress, acceptLanguage: acceptLanguage, languages: languages, requestedLang: requestedLang, authorization: authorization, accountId: accountId, roleId: roleId, userId: userId }, (extendCoreConext.context || {})) })];
179
+ case 2: return [2 /*return*/, __assign(__assign({ db: db, gatewayName: '', isProduction: isProduction, logger: logger, doAuth: doAuth, spaceGw: spaceGw, interserviceApiKey: interserviceApiKey, jwtSecret: jwtSecret, verifyTokenArgs: verifyTokenArgs }, (0, lodash_1.omit)(extendCoreConext, ['context'])), { context: __assign(__assign({}, sharedContext), (extendCoreConext.context || {})) })];
180
+ }
181
+ });
182
+ }); },
183
+ getGatewayContext: function (args) { return __awaiter(void 0, void 0, void 0, function () {
184
+ var extendGatewayConext;
185
+ return __generator(this, function (_a) {
186
+ switch (_a.label) {
187
+ case 0:
188
+ extendGatewayConext = {};
189
+ if (!(typeof getGatewayContext === 'function')) return [3 /*break*/, 2];
190
+ return [4 /*yield*/, getGatewayContext(args)];
191
+ case 1:
192
+ extendGatewayConext = _a.sent();
193
+ _a.label = 2;
194
+ case 2: return [2 /*return*/, {
195
+ db: db,
196
+ isProduction: isProduction,
197
+ logger: logger,
198
+ context: __assign(__assign({}, sharedContext), (extendGatewayConext.context || {})),
199
+ }];
143
200
  }
144
201
  });
145
202
  }); },
@@ -1,5 +1,4 @@
1
- declare const _default: {
2
- ID_FIELD: any;
3
- FIELDS: any;
4
- };
5
- export default _default;
1
+ declare const FIELDS: any;
2
+ declare const HEADERS: any;
3
+ declare const ID_FIELD: any;
4
+ export { ID_FIELD, FIELDS, HEADERS };