@sdflc/backend-helpers 1.0.24 → 1.0.27

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 (40) hide show
  1. package/README.md +175 -0
  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 -20
  5. package/build/{baseCore.js → BaseCore.js} +116 -152
  6. package/build/{baseGateway.d.ts → BaseGateway.d.ts} +15 -11
  7. package/build/{baseGateway.js → BaseGateway.js} +138 -97
  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} +5 -1
  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 +23 -4
  18. package/build/dbSeeder.js +5 -1
  19. package/build/dbTableHelpers.d.ts +2 -0
  20. package/build/dbTableHelpers.js +48 -27
  21. package/build/index.d.ts +9 -11
  22. package/build/index.js +19 -20
  23. package/build/interfaces/ApiContext.d.ts +23 -0
  24. package/build/interfaces/{BaseCoreInterface.js → ApiContext.js} +0 -0
  25. package/build/interfaces/ApiContextInterface.d.ts +5 -1
  26. package/build/interfaces/BaseCorePropsInterface.d.ts +31 -0
  27. package/build/interfaces/{BaseGatewayInterface.js → BaseCorePropsInterface.js} +0 -0
  28. package/build/interfaces/BaseGatewayPropsInterface.d.ts +28 -0
  29. package/build/interfaces/BaseGatewayPropsInterface.js +2 -0
  30. package/build/interfaces/CacheInterface.d.ts +3 -3
  31. package/build/interfaces/JwtTokenSecretAndSettings.d.ts +5 -0
  32. package/build/interfaces/JwtTokenSecretAndSettings.js +2 -0
  33. package/build/interfaces/index.d.ts +4 -2
  34. package/build/resolversHelpers.js +11 -10
  35. package/build/userToken.js +3 -3
  36. package/package.json +68 -68
  37. package/build/baseGatewayHelpers.d.ts +0 -20
  38. package/build/baseGatewayHelpers.js +0 -87
  39. package/build/interfaces/BaseCoreInterface.d.ts +0 -43
  40. package/build/interfaces/BaseGatewayInterface.d.ts +0 -26
@@ -1,26 +1,30 @@
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 returnFields: any[];
7
- constructor(props: BaseGatewayInterface);
8
- 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>;
9
12
  onListFilter(query: any, filterParams: any): Promise<void>;
10
13
  onUpdateFilter(query: any, filterParams: any): Promise<void>;
11
14
  onRemoveFilter(query: any, filterParams: any): Promise<void>;
12
15
  transformOnCreate(args: any): Promise<any>;
13
16
  transformOnUpdate(params: any, where?: any): Promise<any>;
14
17
  transformOnRemove(args?: any): Promise<any>;
15
- getDb(): import("./database").Database;
18
+ getRequestId(): string;
19
+ getContext(): ApiContext;
20
+ getGateways(): any;
21
+ getDb(): Database;
16
22
  getBuilder(): any;
17
- getIdField(): any;
18
- getCore(): BaseCore | undefined;
19
- setCore(core: BaseCore): void;
23
+ getIdField(): string;
20
24
  get(id: any): Promise<any>;
21
25
  getMany(ids: any[]): Promise<any>;
22
26
  list(args?: ListArgsInterface): Promise<any>;
23
- create(args: any): Promise<any>;
27
+ create(args: any): Promise<any[]>;
24
28
  update(where: any, params: any): Promise<any>;
25
29
  updateMany(params: any): Promise<any[]>;
26
30
  increment(where: any, params: any): Promise<any>;
@@ -51,136 +51,167 @@ 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
- var dataCache_1 = require("./dataCache");
56
- var constants_1 = __importDefault(require("./constants"));
57
- var ID_FIELD = constants_1.default.ID_FIELD;
58
- var defaultUpdateRemoveFilter = function (config) { return function (query, params) {
59
- var idName = config.idField || ID_FIELD;
60
- query.where(idName, params[idName]);
61
- }; };
57
+ var utils_1 = require("@sdflc/utils");
58
+ var DataCache_1 = require("./DataCache");
59
+ var constants_1 = require("./constants");
60
+ var DEFAULT_CHUNCK_SIZE = 2500;
62
61
  var BaseGateway = /** @class */ (function () {
63
62
  function BaseGateway(props) {
63
+ this.dateTime = new utils_1.DateTimeHelpers();
64
+ this.dateTimeNow = new Date();
64
65
  this.config = props;
65
- this.returnFields =
66
- Array.isArray(this.config.returnFields) && this.config.returnFields.length > 0
67
- ? this.config.returnFields
68
- : [this.getIdField()];
69
- 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);
70
69
  }
70
+ BaseGateway.prototype.setConfigPart = function (props) {
71
+ Object.assign(this.config, props);
72
+ return this;
73
+ };
71
74
  BaseGateway.prototype.generateId = function (args) {
72
75
  return __awaiter(this, void 0, void 0, function () {
73
76
  return __generator(this, function (_a) {
74
- return [2 /*return*/, typeof this.config.idGenerator === 'function' ? this.config.idGenerator(args) : undefined];
77
+ return [2 /*return*/, (0, uuid_1.v4)()];
75
78
  });
76
79
  });
77
80
  };
78
81
  BaseGateway.prototype.onListFilter = function (query, filterParams) {
79
82
  return __awaiter(this, void 0, void 0, function () {
80
- return __generator(this, function (_a) {
81
- switch (_a.label) {
82
- case 0:
83
- if (!(typeof this.config.filter === 'function')) return [3 /*break*/, 2];
84
- return [4 /*yield*/, this.config.filter(query, filterParams)];
85
- case 1:
86
- _a.sent();
87
- _a.label = 2;
88
- case 2: return [2 /*return*/];
83
+ var _a, hasStatus, hasRemovedAt, hasSpace, activeStatuses, 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, fieldForKeyword = _a.fieldForKeyword;
87
+ // This function should be overriden
88
+ if (hasStatus) {
89
+ query.whereIn(constants_1.FIELDS.STATUS, Array.isArray(filterParams.status) ? filterParams.status : (0, lodash_1.castArray)(activeStatuses));
89
90
  }
91
+ if (hasRemovedAt === true) {
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.spaceId, _b));
96
+ }
97
+ if (filterParams === null || filterParams === void 0 ? void 0 : filterParams.id) {
98
+ query.whereIn(constants_1.FIELDS.ID, (0, lodash_1.castArray)(filterParams === null || filterParams === void 0 ? void 0 : filterParams.id));
99
+ }
100
+ if (fieldForKeyword && filterParams.keyword) {
101
+ query.whereRaw("".concat(fieldForKeyword, " ILIKE ?"), "%".concat(filterParams.keyword, "%"));
102
+ }
103
+ return [2 /*return*/];
90
104
  });
91
105
  });
92
106
  };
93
107
  BaseGateway.prototype.onUpdateFilter = function (query, filterParams) {
94
108
  return __awaiter(this, void 0, void 0, function () {
95
- return __generator(this, function (_a) {
96
- switch (_a.label) {
97
- case 0:
98
- if (!(typeof this.config.updateFilter === 'function')) return [3 /*break*/, 2];
99
- return [4 /*yield*/, this.config.updateFilter(query, filterParams)];
100
- case 1:
101
- _a.sent();
102
- return [3 /*break*/, 4];
103
- case 2: return [4 /*yield*/, defaultUpdateRemoveFilter(this.config)(query, filterParams)];
104
- case 3:
105
- _a.sent();
106
- _a.label = 4;
107
- case 4: return [2 /*return*/];
109
+ var _a, hasStatus, hasVersion, idName;
110
+ return __generator(this, function (_b) {
111
+ _a = this.config, hasStatus = _a.hasStatus, hasVersion = _a.hasVersion;
112
+ idName = this.config.idField || constants_1.ID_FIELD;
113
+ query.where(idName, filterParams[idName]);
114
+ if (hasVersion && filterParams[constants_1.FIELDS.VERSION]) {
115
+ query.where(constants_1.FIELDS.VERSION, filterParams[constants_1.FIELDS.VERSION]);
116
+ }
117
+ if (hasStatus) {
118
+ query.where(constants_1.FIELDS.STATUS, '!=', utils_1.STATUSES.REMOVED);
108
119
  }
120
+ return [2 /*return*/];
109
121
  });
110
122
  });
111
123
  };
112
124
  BaseGateway.prototype.onRemoveFilter = function (query, filterParams) {
113
125
  return __awaiter(this, void 0, void 0, function () {
126
+ var hasStatus, arr;
114
127
  return __generator(this, function (_a) {
115
- switch (_a.label) {
116
- case 0:
117
- if (!(typeof this.config.removeFilter === 'function')) return [3 /*break*/, 2];
118
- return [4 /*yield*/, this.config.removeFilter(query, filterParams)];
119
- case 1:
120
- _a.sent();
121
- return [3 /*break*/, 4];
122
- case 2: return [4 /*yield*/, defaultUpdateRemoveFilter(this.config)(query, filterParams)];
123
- case 3:
124
- _a.sent();
125
- _a.label = 4;
126
- case 4: return [2 /*return*/];
128
+ hasStatus = this.config.hasStatus;
129
+ arr = (0, lodash_1.castArray)(filterParams);
130
+ query = query.whereIn(constants_1.FIELDS.ID, arr.map(function (item) { return item[constants_1.FIELDS.ID]; }));
131
+ if (hasStatus === true) {
132
+ query.where(constants_1.FIELDS.STATUS, '!=', utils_1.STATUSES.REMOVED);
127
133
  }
134
+ return [2 /*return*/];
128
135
  });
129
136
  });
130
137
  };
131
138
  BaseGateway.prototype.transformOnCreate = function (args) {
132
139
  return __awaiter(this, void 0, void 0, function () {
133
- return __generator(this, function (_a) {
134
- switch (_a.label) {
135
- case 0:
136
- if (!(typeof this.config.insertFormatter === 'function')) return [3 /*break*/, 2];
137
- return [4 /*yield*/, this.config.insertFormatter(args)];
138
- case 1: return [2 /*return*/, _a.sent()];
139
- case 2: return [2 /*return*/, args];
140
+ var _a, hasCreatedAt, hasCreatedBy;
141
+ return __generator(this, function (_b) {
142
+ _a = this.config, hasCreatedAt = _a.hasCreatedAt, hasCreatedBy = _a.hasCreatedBy;
143
+ if (hasCreatedAt) {
144
+ args[constants_1.FIELDS.CREATED_AT] = this.dateTime.dbFormat(this.dateTimeNow);
140
145
  }
146
+ if (hasCreatedBy) {
147
+ if (args[constants_1.FIELDS.CREATED_BY] === undefined) {
148
+ args[constants_1.FIELDS.CREATED_BY] = this.getContext().userId;
149
+ }
150
+ }
151
+ return [2 /*return*/, args];
141
152
  });
142
153
  });
143
154
  };
144
155
  BaseGateway.prototype.transformOnUpdate = function (params, where) {
145
156
  return __awaiter(this, void 0, void 0, function () {
146
- return __generator(this, function (_a) {
147
- switch (_a.label) {
148
- case 0:
149
- if (!(typeof this.config.updateFormatter === 'function')) return [3 /*break*/, 2];
150
- return [4 /*yield*/, this.config.updateFormatter(params, where)];
151
- case 1: return [2 /*return*/, _a.sent()];
152
- case 2: return [2 /*return*/, params];
157
+ var _a, hasUpdatedAt, hasUpdatedBy;
158
+ return __generator(this, function (_b) {
159
+ _a = this.config, hasUpdatedAt = _a.hasUpdatedAt, hasUpdatedBy = _a.hasUpdatedBy;
160
+ if (hasUpdatedAt) {
161
+ params[constants_1.FIELDS.UPDATED_AT] = this.dateTime.dbFormat(this.dateTimeNow);
162
+ }
163
+ if (hasUpdatedBy) {
164
+ if (params[constants_1.FIELDS.UPDATED_BY] === undefined) {
165
+ params[constants_1.FIELDS.UPDATED_BY] = this.getContext().userId;
166
+ }
153
167
  }
168
+ return [2 /*return*/, params];
154
169
  });
155
170
  });
156
171
  };
157
172
  BaseGateway.prototype.transformOnRemove = function (args) {
158
173
  return __awaiter(this, void 0, void 0, function () {
159
- return __generator(this, function (_a) {
160
- switch (_a.label) {
161
- case 0:
162
- if (!(typeof this.config.removeFormatter === 'function')) return [3 /*break*/, 2];
163
- return [4 /*yield*/, this.config.removeFormatter(args)];
164
- case 1: return [2 /*return*/, _a.sent()];
165
- case 2: return [2 /*return*/, args];
174
+ var _a, hasRemovedAt, hasRemovedAtStr, hasStatus, hasRemovedBy, removalTime, obj;
175
+ return __generator(this, function (_b) {
176
+ _a = this.config, hasRemovedAt = _a.hasRemovedAt, hasRemovedAtStr = _a.hasRemovedAtStr, hasStatus = _a.hasStatus, hasRemovedBy = _a.hasRemovedBy;
177
+ removalTime = (0, dayjs_1.default)();
178
+ obj = __assign({}, args);
179
+ if (hasRemovedAt) {
180
+ obj[constants_1.FIELDS.REMOVED_AT] = removalTime.toDate();
181
+ }
182
+ if (hasRemovedAtStr === true) {
183
+ obj[constants_1.FIELDS.REMOVED_AT_STR] = removalTime.format('YYYYMMDDTHHmmssZ');
184
+ }
185
+ if (hasStatus === true) {
186
+ obj[constants_1.FIELDS.STATUS] = utils_1.STATUSES.REMOVED;
187
+ }
188
+ if (hasRemovedBy) {
189
+ if (args[constants_1.FIELDS.REMOVED_BY] === undefined) {
190
+ args[constants_1.FIELDS.REMOVED_BY] = this.getContext().userId;
191
+ }
166
192
  }
193
+ return [2 /*return*/, obj];
167
194
  });
168
195
  });
169
196
  };
197
+ BaseGateway.prototype.getRequestId = function () {
198
+ return this.config.context.requestId;
199
+ };
200
+ BaseGateway.prototype.getContext = function () {
201
+ return this.config.context;
202
+ };
203
+ BaseGateway.prototype.getGateways = function () {
204
+ return this.config.context.gateways || {};
205
+ };
170
206
  BaseGateway.prototype.getDb = function () {
171
207
  return this.config.db;
172
208
  };
173
209
  BaseGateway.prototype.getBuilder = function () {
174
- return this.getDb().getBuilder(this.config.table);
210
+ var _a;
211
+ return (_a = this.getDb()) === null || _a === void 0 ? void 0 : _a.getBuilder(this.config.table);
175
212
  };
176
213
  BaseGateway.prototype.getIdField = function () {
177
- return this.config.idField || ID_FIELD;
178
- };
179
- BaseGateway.prototype.getCore = function () {
180
- return this.config.core;
181
- };
182
- BaseGateway.prototype.setCore = function (core) {
183
- this.config.core = core;
214
+ return this.config.idField || constants_1.ID_FIELD;
184
215
  };
185
216
  BaseGateway.prototype.get = function (id) {
186
217
  return __awaiter(this, void 0, void 0, function () {
@@ -237,38 +268,48 @@ var BaseGateway = /** @class */ (function () {
237
268
  });
238
269
  };
239
270
  BaseGateway.prototype.create = function (args) {
271
+ var _a;
240
272
  return __awaiter(this, void 0, void 0, function () {
241
- var objects, idx, len, arg, id, obj, items;
242
- return __generator(this, function (_a) {
243
- switch (_a.label) {
273
+ var objects, idx, len, arg, id, obj, result, chunks, idx, len, items;
274
+ return __generator(this, function (_b) {
275
+ switch (_b.label) {
244
276
  case 0:
245
- objects = [];
246
- if (!Array.isArray(args)) {
247
- args = [args];
248
- }
249
- if (args.length === 0) {
277
+ objects = (0, lodash_1.castArray)(args);
278
+ if (!args || objects.length === 0) {
250
279
  return [2 /*return*/, []];
251
280
  }
252
281
  idx = 0, len = args.length;
253
- _a.label = 1;
282
+ _b.label = 1;
254
283
  case 1:
255
284
  if (!(idx < len)) return [3 /*break*/, 5];
256
285
  arg = args[idx];
257
286
  return [4 /*yield*/, this.generateId(arg)];
258
287
  case 2:
259
- id = _a.sent();
288
+ id = _b.sent();
260
289
  return [4 /*yield*/, this.transformOnCreate(__assign({ id: id }, arg))];
261
290
  case 3:
262
- obj = _a.sent();
291
+ obj = _b.sent();
263
292
  objects.push(obj);
264
- _a.label = 4;
293
+ _b.label = 4;
265
294
  case 4:
266
295
  ++idx;
267
296
  return [3 /*break*/, 1];
268
- case 5: return [4 /*yield*/, this.getBuilder().insert(objects).returning(this.returnFields)];
297
+ case 5:
298
+ result = [];
299
+ chunks = (0, utils_1.arrToChunks)(objects, ((_a = this.config) === null || _a === void 0 ? void 0 : _a.insertChunkSize) || DEFAULT_CHUNCK_SIZE);
300
+ idx = 0, len = chunks.length;
301
+ _b.label = 6;
269
302
  case 6:
270
- items = _a.sent();
271
- return [2 /*return*/, items];
303
+ if (!(idx < len)) return [3 /*break*/, 9];
304
+ return [4 /*yield*/, this.getBuilder().insert(chunks[idx]).returning(this.config.returnFields)];
305
+ case 7:
306
+ items = _b.sent();
307
+ result.push.apply(result, items);
308
+ _b.label = 8;
309
+ case 8:
310
+ ++idx;
311
+ return [3 /*break*/, 6];
312
+ case 9: return [2 /*return*/, result];
272
313
  }
273
314
  });
274
315
  });
@@ -282,7 +323,7 @@ var BaseGateway = /** @class */ (function () {
282
323
  case 0: return [4 /*yield*/, this.transformOnUpdate(params, where)];
283
324
  case 1:
284
325
  object = _a.sent();
285
- query = this.getBuilder().update(object).returning(this.returnFields);
326
+ query = this.getBuilder().update(object).returning(this.config.returnFields);
286
327
  return [4 /*yield*/, this.onUpdateFilter(query, where)];
287
328
  case 2:
288
329
  _a.sent();
@@ -339,7 +380,7 @@ var BaseGateway = /** @class */ (function () {
339
380
  case 0: return [4 /*yield*/, this.transformOnUpdate(params, where)];
340
381
  case 1:
341
382
  object = _a.sent();
342
- query = this.getBuilder().increment(object).returning(this.returnFields);
383
+ query = this.getBuilder().increment(object).returning(this.config.returnFields);
343
384
  return [4 /*yield*/, this.onUpdateFilter(query, where)];
344
385
  case 2:
345
386
  _a.sent();
@@ -363,7 +404,7 @@ var BaseGateway = /** @class */ (function () {
363
404
  case 0: return [4 /*yield*/, this.transformOnUpdate(params, where)];
364
405
  case 1:
365
406
  object = _a.sent();
366
- query = this.getBuilder().decrement(object).returning(this.returnFields);
407
+ query = this.getBuilder().decrement(object).returning(this.config.returnFields);
367
408
  return [4 /*yield*/, this.onUpdateFilter(query, where)];
368
409
  case 2:
369
410
  _a.sent();
@@ -395,7 +436,7 @@ var BaseGateway = /** @class */ (function () {
395
436
  idField = this.getIdField();
396
437
  return [4 /*yield*/, this.getBuilder()
397
438
  .insert((0, lodash_1.castArray)(params))
398
- .returning(this.returnFields)
439
+ .returning(this.config.returnFields)
399
440
  .onConflict(this.config.setFields || idField)
400
441
  .merge()];
401
442
  case 1:
@@ -416,13 +457,13 @@ var BaseGateway = /** @class */ (function () {
416
457
  case 0:
417
458
  query = this.getBuilder();
418
459
  if (!hardRemove) return [3 /*break*/, 1];
419
- query.delete(this.returnFields);
460
+ query.delete(this.config.returnFields);
420
461
  return [3 /*break*/, 3];
421
462
  case 1:
422
463
  _b = (_a = query).update;
423
464
  return [4 /*yield*/, this.transformOnRemove()];
424
465
  case 2:
425
- _b.apply(_a, [_c.sent()]).returning(this.returnFields);
466
+ _b.apply(_a, [_c.sent()]).returning(this.config.returnFields);
426
467
  _c.label = 3;
427
468
  case 3: return [4 /*yield*/, this.onRemoveFilter(query, where)];
428
469
  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,7 +1,11 @@
1
1
  "use strict";
2
2
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
3
  if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
5
9
  }) : (function(o, m, k, k2) {
6
10
  if (k2 === undefined) k2 = k;
7
11
  o[k2] = m[k];
@@ -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, gwSpace, 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, gwSpace = _a.gwSpace, 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, gwSpace: gwSpace, 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
  }); },