@sdflc/backend-helpers 1.0.26 → 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 (37) hide show
  1. package/build/{baseController.d.ts → BaseController.d.ts} +0 -0
  2. package/build/{baseController.js → BaseController.js} +0 -0
  3. package/build/{baseCore.d.ts → BaseCore.d.ts} +13 -19
  4. package/build/{baseCore.js → BaseCore.js} +112 -153
  5. package/build/{baseGateway.d.ts → BaseGateway.d.ts} +14 -11
  6. package/build/{baseGateway.js → BaseGateway.js} +124 -95
  7. package/build/{dataCache.d.ts → DataCache.d.ts} +0 -0
  8. package/build/{dataCache.js → DataCache.js} +2 -2
  9. package/build/{database.d.ts → Database.d.ts} +0 -0
  10. package/build/{database.js → Database.js} +0 -0
  11. package/build/{dbMigratorAndSeeder.d.ts → DbMigratorAndSeeder.d.ts} +0 -0
  12. package/build/{dbMigratorAndSeeder.js → DbMigratorAndSeeder.js} +0 -0
  13. package/build/apiContext.d.ts +3 -3
  14. package/build/apiContext.js +89 -32
  15. package/build/constants.d.ts +4 -5
  16. package/build/constants.js +18 -4
  17. package/build/dbTableHelpers.js +29 -33
  18. package/build/index.d.ts +8 -10
  19. package/build/index.js +17 -20
  20. package/build/interfaces/ApiContext.d.ts +23 -0
  21. package/build/interfaces/{BaseCoreInterface.js → ApiContext.js} +0 -0
  22. package/build/interfaces/ApiContextInterface.d.ts +5 -1
  23. package/build/interfaces/BaseCorePropsInterface.d.ts +31 -0
  24. package/build/interfaces/{BaseGatewayInterface.js → BaseCorePropsInterface.js} +0 -0
  25. package/build/interfaces/BaseGatewayPropsInterface.d.ts +28 -0
  26. package/build/interfaces/BaseGatewayPropsInterface.js +2 -0
  27. package/build/interfaces/CacheInterface.d.ts +3 -3
  28. package/build/interfaces/JwtTokenSecretAndSettings.d.ts +5 -0
  29. package/build/interfaces/JwtTokenSecretAndSettings.js +2 -0
  30. package/build/interfaces/index.d.ts +4 -2
  31. package/build/resolversHelpers.js +11 -10
  32. package/build/userToken.js +3 -3
  33. package/package.json +2 -2
  34. package/build/baseGatewayHelpers.d.ts +0 -20
  35. package/build/baseGatewayHelpers.js +0 -87
  36. package/build/interfaces/BaseCoreInterface.d.ts +0 -43
  37. 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,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
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, 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));
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));
92
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*/];
93
104
  });
94
105
  });
95
106
  };
96
107
  BaseGateway.prototype.onUpdateFilter = function (query, filterParams) {
97
108
  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*/];
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);
111
119
  }
120
+ return [2 /*return*/];
112
121
  });
113
122
  });
114
123
  };
115
124
  BaseGateway.prototype.onRemoveFilter = function (query, filterParams) {
116
125
  return __awaiter(this, void 0, void 0, function () {
126
+ var hasStatus, arr;
117
127
  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*/];
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);
130
133
  }
134
+ return [2 /*return*/];
131
135
  });
132
136
  });
133
137
  };
134
138
  BaseGateway.prototype.transformOnCreate = function (args) {
135
139
  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];
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);
145
+ }
146
+ if (hasCreatedBy) {
147
+ if (args[constants_1.FIELDS.CREATED_BY] === undefined) {
148
+ args[constants_1.FIELDS.CREATED_BY] = this.getContext().userId;
149
+ }
143
150
  }
151
+ return [2 /*return*/, args];
144
152
  });
145
153
  });
146
154
  };
147
155
  BaseGateway.prototype.transformOnUpdate = function (params, where) {
148
156
  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];
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);
156
162
  }
163
+ if (hasUpdatedBy) {
164
+ if (params[constants_1.FIELDS.UPDATED_BY] === undefined) {
165
+ params[constants_1.FIELDS.UPDATED_BY] = this.getContext().userId;
166
+ }
167
+ }
168
+ return [2 /*return*/, params];
157
169
  });
158
170
  });
159
171
  };
160
172
  BaseGateway.prototype.transformOnRemove = function (args) {
161
173
  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];
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;
169
187
  }
188
+ if (hasRemovedBy) {
189
+ if (args[constants_1.FIELDS.REMOVED_BY] === undefined) {
190
+ args[constants_1.FIELDS.REMOVED_BY] = this.getContext().userId;
191
+ }
192
+ }
193
+ return [2 /*return*/, obj];
170
194
  });
171
195
  });
172
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
+ };
173
206
  BaseGateway.prototype.getDb = function () {
174
207
  return this.config.db;
175
208
  };
176
209
  BaseGateway.prototype.getBuilder = function () {
177
- 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);
178
212
  };
179
213
  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;
214
+ return this.config.idField || constants_1.ID_FIELD;
187
215
  };
188
216
  BaseGateway.prototype.get = function (id) {
189
217
  return __awaiter(this, void 0, void 0, function () {
@@ -240,43 +268,44 @@ var BaseGateway = /** @class */ (function () {
240
268
  });
241
269
  };
242
270
  BaseGateway.prototype.create = function (args) {
271
+ var _a;
243
272
  return __awaiter(this, void 0, void 0, function () {
244
273
  var objects, idx, len, arg, id, obj, result, chunks, idx, len, items;
245
- return __generator(this, function (_a) {
246
- switch (_a.label) {
274
+ return __generator(this, function (_b) {
275
+ switch (_b.label) {
247
276
  case 0:
248
277
  objects = (0, lodash_1.castArray)(args);
249
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
297
  case 5:
269
298
  result = [];
270
- chunks = (0, utils_1.arrToChunks)(objects, this.insertChunkSize);
299
+ chunks = (0, utils_1.arrToChunks)(objects, ((_a = this.config) === null || _a === void 0 ? void 0 : _a.insertChunkSize) || DEFAULT_CHUNCK_SIZE);
271
300
  idx = 0, len = chunks.length;
272
- _a.label = 6;
301
+ _b.label = 6;
273
302
  case 6:
274
303
  if (!(idx < len)) return [3 /*break*/, 9];
275
- return [4 /*yield*/, this.getBuilder().insert(chunks[idx]).returning(this.returnFields)];
304
+ return [4 /*yield*/, this.getBuilder().insert(chunks[idx]).returning(this.config.returnFields)];
276
305
  case 7:
277
- items = _a.sent();
306
+ items = _b.sent();
278
307
  result.push.apply(result, items);
279
- _a.label = 8;
308
+ _b.label = 8;
280
309
  case 8:
281
310
  ++idx;
282
311
  return [3 /*break*/, 6];
@@ -294,7 +323,7 @@ var BaseGateway = /** @class */ (function () {
294
323
  case 0: return [4 /*yield*/, this.transformOnUpdate(params, where)];
295
324
  case 1:
296
325
  object = _a.sent();
297
- query = this.getBuilder().update(object).returning(this.returnFields);
326
+ query = this.getBuilder().update(object).returning(this.config.returnFields);
298
327
  return [4 /*yield*/, this.onUpdateFilter(query, where)];
299
328
  case 2:
300
329
  _a.sent();
@@ -351,7 +380,7 @@ var BaseGateway = /** @class */ (function () {
351
380
  case 0: return [4 /*yield*/, this.transformOnUpdate(params, where)];
352
381
  case 1:
353
382
  object = _a.sent();
354
- query = this.getBuilder().increment(object).returning(this.returnFields);
383
+ query = this.getBuilder().increment(object).returning(this.config.returnFields);
355
384
  return [4 /*yield*/, this.onUpdateFilter(query, where)];
356
385
  case 2:
357
386
  _a.sent();
@@ -375,7 +404,7 @@ var BaseGateway = /** @class */ (function () {
375
404
  case 0: return [4 /*yield*/, this.transformOnUpdate(params, where)];
376
405
  case 1:
377
406
  object = _a.sent();
378
- query = this.getBuilder().decrement(object).returning(this.returnFields);
407
+ query = this.getBuilder().decrement(object).returning(this.config.returnFields);
379
408
  return [4 /*yield*/, this.onUpdateFilter(query, where)];
380
409
  case 2:
381
410
  _a.sent();
@@ -407,7 +436,7 @@ var BaseGateway = /** @class */ (function () {
407
436
  idField = this.getIdField();
408
437
  return [4 /*yield*/, this.getBuilder()
409
438
  .insert((0, lodash_1.castArray)(params))
410
- .returning(this.returnFields)
439
+ .returning(this.config.returnFields)
411
440
  .onConflict(this.config.setFields || idField)
412
441
  .merge()];
413
442
  case 1:
@@ -428,13 +457,13 @@ var BaseGateway = /** @class */ (function () {
428
457
  case 0:
429
458
  query = this.getBuilder();
430
459
  if (!hardRemove) return [3 /*break*/, 1];
431
- query.delete(this.returnFields);
460
+ query.delete(this.config.returnFields);
432
461
  return [3 /*break*/, 3];
433
462
  case 1:
434
463
  _b = (_a = query).update;
435
464
  return [4 /*yield*/, this.transformOnRemove()];
436
465
  case 2:
437
- _b.apply(_a, [_c.sent()]).returning(this.returnFields);
466
+ _b.apply(_a, [_c.sent()]).returning(this.config.returnFields);
438
467
  _c.label = 3;
439
468
  case 3: return [4 /*yield*/, this.onRemoveFilter(query, where)];
440
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,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
  }); },
@@ -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 };