@sdflc/backend-helpers 1.0.14 → 1.0.18

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.
@@ -4,3 +4,8 @@ import { ApiContextInterface } from './interfaces';
4
4
  * @returns {object} A context object with all available cores
5
5
  */
6
6
  export declare const createApiContext: (args: ApiContextInterface) => any;
7
+ /**
8
+ * Creates default a GraphQL context object with all avilable cores.
9
+ * @returns {object} A context object with all available cores
10
+ */
11
+ export declare const createContextDefault: (args: any) => any;
@@ -11,9 +11,11 @@ var __assign = (this && this.__assign) || function () {
11
11
  return __assign.apply(this, arguments);
12
12
  };
13
13
  Object.defineProperty(exports, "__esModule", { value: true });
14
- exports.createApiContext = void 0;
14
+ exports.createContextDefault = exports.createApiContext = void 0;
15
15
  var lodash_1 = require("lodash");
16
16
  var uuid_1 = require("uuid");
17
+ var utils_1 = require("@sdflc/utils");
18
+ var database_1 = require("./database");
17
19
  /**
18
20
  * Creates a GraphQL context object with all available cores.
19
21
  * @returns {object} A context object with all available cores
@@ -34,3 +36,57 @@ var createApiContext = function (args) {
34
36
  return context;
35
37
  };
36
38
  exports.createApiContext = createApiContext;
39
+ /**
40
+ * Creates default a GraphQL context object with all avilable cores.
41
+ * @returns {object} A context object with all available cores
42
+ */
43
+ var createContextDefault = function (args) {
44
+ var _a = args || {}, knexConfig = _a.knexConfig, dbSchema = _a.dbSchema, cores = _a.cores, req = _a.req;
45
+ var authorization = req.headers['authorization'];
46
+ var spaceId = req.headers['x-space-id'];
47
+ var apiKey = req.headers['x-api-key'];
48
+ var accountId = req.headers['x-account-id'];
49
+ var roleId = req.headers['x-role-id'];
50
+ var userId = req.headers['x-user-id'];
51
+ var userAgent = req.headers['user-agent'];
52
+ var referer = req.headers['referer'];
53
+ var ipAddress = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
54
+ var acceptLanguage = req.headers['accept-language'];
55
+ var languages = utils_1.extractLanguages(acceptLanguage);
56
+ var requestedLang = req.query['lang'];
57
+ var requestId = uuid_1.v4();
58
+ var db = new database_1.Database({
59
+ knexConfig: knexConfig,
60
+ dbSchema: dbSchema,
61
+ });
62
+ return exports.createApiContext({
63
+ cores: cores,
64
+ req: req,
65
+ requestId: requestId,
66
+ extendContext: function (_a) {
67
+ var context = _a.context /*, req */;
68
+ context.db = db;
69
+ },
70
+ getCoreContext: function ( /*args: any*/) {
71
+ // TODO: const { req } = args;
72
+ return {
73
+ db: db,
74
+ context: {
75
+ spaceId: spaceId,
76
+ apiKey: apiKey,
77
+ userAgent: userAgent,
78
+ referer: referer,
79
+ ipAddress: ipAddress,
80
+ acceptLanguage: acceptLanguage,
81
+ languages: languages,
82
+ requestedLang: requestedLang,
83
+ authorization: authorization,
84
+ accountId: accountId,
85
+ roleId: roleId,
86
+ userId: userId,
87
+ },
88
+ };
89
+ },
90
+ });
91
+ };
92
+ exports.createContextDefault = createContextDefault;
@@ -1,13 +1,12 @@
1
- import { BaseCoreValidatorsInterface } from './interfaces/BaseCoreValidatorsInterface';
2
1
  import { Logger } from '@sdflc/utils';
3
- import { BaseCoreInterface, DoingWhatInterface, CoreActionInterface } from './interfaces';
2
+ import { BaseCoreInterface, BaseCoreDoingWhatInterface, CoreActionInterface, BaseCoreValidatorsInterface } from './interfaces';
4
3
  import { BaseGateway } from './baseGateway';
5
4
  import { Database } from './database';
6
5
  declare class BaseCore {
7
6
  protected db: Database;
8
7
  protected context: any;
9
8
  protected gateway?: BaseGateway;
10
- protected doingWhat?: DoingWhatInterface;
9
+ protected doingWhat?: BaseCoreDoingWhatInterface;
11
10
  protected logger: Logger;
12
11
  protected name?: string;
13
12
  protected gateways?: any;
@@ -27,6 +26,7 @@ declare class BaseCore {
27
26
  protected afterSet: any;
28
27
  protected afterRemove: any;
29
28
  protected afterRemoveMany: any;
29
+ protected onException: any;
30
30
  protected requestId: string;
31
31
  protected validators: BaseCoreValidatorsInterface;
32
32
  protected authenticate: any;
package/build/baseCore.js CHANGED
@@ -59,7 +59,7 @@ var ACCESS_RIGHTS = constants_1.default.ACCESS_RIGHTS;
59
59
  var defaultAfterAndBefore = function (params) {
60
60
  return params;
61
61
  };
62
- var defaultValidate = function (params, gateways) {
62
+ var defaultValidate = function (params, opt) {
63
63
  return [true, {}];
64
64
  };
65
65
  var defaultValidators = {
@@ -106,6 +106,7 @@ var BaseCore = /** @class */ (function () {
106
106
  this.afterSet = typeof props.afterSet === 'function' ? props.afterSet : defaultAfterAndBefore;
107
107
  this.afterRemove = typeof props.afterRemove === 'function' ? props.afterRemove : defaultAfterAndBefore;
108
108
  this.afterRemoveMany = typeof props.afterRemoveMany === 'function' ? props.afterRemoveMany : defaultAfterAndBefore;
109
+ this.onException = typeof props.onException === 'function' ? props.onException : defaultAfterAndBefore;
109
110
  this.validators = utils_2.setFunctions((props === null || props === void 0 ? void 0 : props.validators) || {}, this.validators);
110
111
  this.authenticate = typeof props.authenticate === 'function' ? props.authenticate : defaultAuth;
111
112
  this.doAuth = props.doAuth === true;
@@ -201,19 +202,25 @@ var BaseCore = /** @class */ (function () {
201
202
  };
202
203
  BaseCore.prototype.runAction = function (opt) {
203
204
  return __awaiter(this, void 0, void 0, function () {
204
- var _a, args, validate, doAuth, action, hasTransaction, doingWhat, sameRequest, step, setStep, _b, authResult, errMsg, validatedItems, valideResult, result_1, result, ex_1, what;
205
+ var _a, args, validate, doAuth, action, hasTransaction, doingWhat, sameRequest, step, setStep, actionOpt, _b, authResult, errMsg, validatedItems, valideResult, result_1, result, ex_1, what;
205
206
  return __generator(this, function (_c) {
206
207
  switch (_c.label) {
207
208
  case 0:
208
209
  _a = opt || {}, args = _a.args, validate = _a.validate, doAuth = _a.doAuth, action = _a.action, hasTransaction = _a.hasTransaction, doingWhat = _a.doingWhat;
209
- sameRequest = this.requestId && (args === null || args === void 0 ? void 0 : args.requestId) === this.requestId;
210
+ sameRequest = !!this.requestId && (args === null || args === void 0 ? void 0 : args.requestId) === this.requestId;
210
211
  step = doingWhat || '';
211
212
  setStep = function (stepName) {
212
213
  step = stepName;
213
214
  };
215
+ actionOpt = {
216
+ core: this,
217
+ setStep: setStep,
218
+ sameRequest: sameRequest,
219
+ hasTransaction: hasTransaction,
220
+ };
214
221
  _c.label = 1;
215
222
  case 1:
216
- _c.trys.push([1, 11, , 14]);
223
+ _c.trys.push([1, 11, , 15]);
217
224
  if (!!sameRequest) return [3 /*break*/, 5];
218
225
  if (!hasTransaction) return [3 /*break*/, 3];
219
226
  return [4 /*yield*/, this.db.startTransaction()];
@@ -222,7 +229,7 @@ var BaseCore = /** @class */ (function () {
222
229
  _c.label = 3;
223
230
  case 3:
224
231
  if (!(doAuth === true || (doAuth == null && this.doAuth))) return [3 /*break*/, 5];
225
- return [4 /*yield*/, this.authenticate(opt)];
232
+ return [4 /*yield*/, this.authenticate(opt, actionOpt)];
226
233
  case 4:
227
234
  _b = _c.sent(), authResult = _b[0], errMsg = _b[1];
228
235
  if (!authResult) {
@@ -232,7 +239,7 @@ var BaseCore = /** @class */ (function () {
232
239
  case 5:
233
240
  validatedItems = {};
234
241
  if (!(typeof validate === 'function')) return [3 /*break*/, 8];
235
- return [4 /*yield*/, validate(args, this.getGateways())];
242
+ return [4 /*yield*/, validate(args, actionOpt)];
236
243
  case 6:
237
244
  valideResult = _c.sent();
238
245
  result_1 = valideResult;
@@ -249,7 +256,7 @@ var BaseCore = /** @class */ (function () {
249
256
  // if there was an error then `result` is expected to be an object with the same structure as the checkit library does
250
257
  _c.sent();
251
258
  return [2 /*return*/, result_1.code != null ? result_1 : new api_helpers_1.OpResult({ code: api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED })];
252
- case 8: return [4 /*yield*/, action(args, { setStep: setStep, validatedItems: validatedItems, sameRequest: sameRequest })];
259
+ case 8: return [4 /*yield*/, action(args, __assign(__assign({}, actionOpt), { validatedItems: validatedItems }))];
253
260
  case 9:
254
261
  result = _c.sent();
255
262
  return [4 /*yield*/, this.checkResult({ hasTransaction: hasTransaction, result: result, sameRequest: sameRequest })];
@@ -263,7 +270,9 @@ var BaseCore = /** @class */ (function () {
263
270
  case 12:
264
271
  _c.sent();
265
272
  _c.label = 13;
266
- case 13:
273
+ case 13: return [4 /*yield*/, this.onException(args, __assign(__assign({}, actionOpt), { doingWhat: doingWhat, exception: ex_1 }))];
274
+ case 14:
275
+ _c.sent();
267
276
  what = doingWhat;
268
277
  if (doingWhat !== step) {
269
278
  what = {
@@ -271,7 +280,7 @@ var BaseCore = /** @class */ (function () {
271
280
  };
272
281
  }
273
282
  return [2 /*return*/, this.exceptionFailure(ex_1, what)];
274
- case 14: return [2 /*return*/];
283
+ case 15: return [2 /*return*/];
275
284
  }
276
285
  });
277
286
  });
@@ -285,24 +294,24 @@ var BaseCore = /** @class */ (function () {
285
294
  args: args,
286
295
  validate: this.validators.list,
287
296
  accessRights: [ACCESS_RIGHTS.LIST],
288
- action: function (args) { return __awaiter(_this, void 0, void 0, function () {
297
+ action: function (args, opt) { return __awaiter(_this, void 0, void 0, function () {
289
298
  var object, items, result;
290
299
  var _a;
291
300
  return __generator(this, function (_b) {
292
301
  switch (_b.label) {
293
302
  case 0:
294
303
  this.logger.log("Requesting a list for " + this.name + ":", args);
295
- return [4 /*yield*/, this.beforeList(args, this.getGateways())];
304
+ return [4 /*yield*/, this.beforeList(args, opt)];
296
305
  case 1:
297
306
  object = _b.sent();
298
307
  return [4 /*yield*/, ((_a = this.gateway) === null || _a === void 0 ? void 0 : _a.list(object))];
299
308
  case 2:
300
309
  items = _b.sent();
301
- return [4 /*yield*/, this.afterList(items, this.getGateways())];
310
+ return [4 /*yield*/, this.afterList(items, opt)];
302
311
  case 3:
303
312
  result = _b.sent();
304
313
  // ON NO DATA RETURN EMPTY CODE
305
- return [2 /*return*/, this.success(result)];
314
+ return [2 /*return*/, this.success(result /*, result.length > 0 OP_RESULT_CODES.OK : OP_RESULT_CODES.*/)];
306
315
  }
307
316
  });
308
317
  }); },
@@ -381,7 +390,7 @@ var BaseCore = /** @class */ (function () {
381
390
  args: args,
382
391
  validate: this.validators.create,
383
392
  accessRights: [ACCESS_RIGHTS.CREATE],
384
- action: function (args) { return __awaiter(_this, void 0, void 0, function () {
393
+ action: function (args, opt) { return __awaiter(_this, void 0, void 0, function () {
385
394
  var params, object, item, result;
386
395
  var _a;
387
396
  return __generator(this, function (_b) {
@@ -389,20 +398,20 @@ var BaseCore = /** @class */ (function () {
389
398
  case 0:
390
399
  params = (args || {}).params;
391
400
  this.logger.log("Requesting creation of an item for " + this.name + ":", args);
392
- return [4 /*yield*/, this.beforeCreate(params, this.getGateways())];
401
+ return [4 /*yield*/, this.beforeCreate(params, opt)];
393
402
  case 1:
394
403
  object = _b.sent();
395
404
  return [4 /*yield*/, ((_a = this.gateway) === null || _a === void 0 ? void 0 : _a.create(object))];
396
405
  case 2:
397
406
  item = _b.sent();
398
- return [4 /*yield*/, this.afterCreate(item, this.getGateways())];
407
+ return [4 /*yield*/, this.afterCreate(item, opt)];
399
408
  case 3:
400
409
  result = _b.sent();
401
410
  return [2 /*return*/, this.success(result)];
402
411
  }
403
412
  });
404
413
  }); },
405
- hasTransaction: false,
414
+ hasTransaction: true,
406
415
  doingWhat: (_c = (_b = (_a = this.doingWhat) === null || _a === void 0 ? void 0 : _a.create) !== null && _b !== void 0 ? _b : this.name) !== null && _c !== void 0 ? _c : 'creating an item',
407
416
  })];
408
417
  });
@@ -417,7 +426,7 @@ var BaseCore = /** @class */ (function () {
417
426
  args: args,
418
427
  validate: this.validators.createMany,
419
428
  accessRights: [ACCESS_RIGHTS.CREATE],
420
- action: function (args) { return __awaiter(_this, void 0, void 0, function () {
429
+ action: function (args, opt) { return __awaiter(_this, void 0, void 0, function () {
421
430
  var params, objects, items, result;
422
431
  var _a;
423
432
  return __generator(this, function (_b) {
@@ -425,20 +434,20 @@ var BaseCore = /** @class */ (function () {
425
434
  case 0:
426
435
  params = (args || {}).params;
427
436
  this.logger.log("Requesting creation of multiple items for " + this.name + ":", args);
428
- return [4 /*yield*/, this.beforeCreateMany(params, this.getGateways())];
437
+ return [4 /*yield*/, this.beforeCreateMany(params, opt)];
429
438
  case 1:
430
439
  objects = _b.sent();
431
440
  return [4 /*yield*/, ((_a = this.gateway) === null || _a === void 0 ? void 0 : _a.create(objects))];
432
441
  case 2:
433
442
  items = _b.sent();
434
- return [4 /*yield*/, this.afterCreateMany(items, this.getGateways())];
443
+ return [4 /*yield*/, this.afterCreateMany(items, opt)];
435
444
  case 3:
436
445
  result = _b.sent();
437
446
  return [2 /*return*/, this.success(result)];
438
447
  }
439
448
  });
440
449
  }); },
441
- hasTransaction: false,
450
+ hasTransaction: true,
442
451
  doingWhat: (_c = (_b = (_a = this.doingWhat) === null || _a === void 0 ? void 0 : _a.createMany) !== null && _b !== void 0 ? _b : this.name) !== null && _c !== void 0 ? _c : 'creating multiple items',
443
452
  })];
444
453
  });
@@ -453,7 +462,7 @@ var BaseCore = /** @class */ (function () {
453
462
  args: args,
454
463
  validate: this.validators.update,
455
464
  accessRights: [ACCESS_RIGHTS.UPDATE],
456
- action: function (args) { return __awaiter(_this, void 0, void 0, function () {
465
+ action: function (args, opt) { return __awaiter(_this, void 0, void 0, function () {
457
466
  var _a, where, params, object, item, result;
458
467
  var _b;
459
468
  return __generator(this, function (_c) {
@@ -461,20 +470,20 @@ var BaseCore = /** @class */ (function () {
461
470
  case 0:
462
471
  _a = args || {}, where = _a.where, params = _a.params;
463
472
  this.logger.log("Requesting update of an item for " + this.name + ":", args);
464
- return [4 /*yield*/, this.beforeUpdate(params, this.getGateways())];
473
+ return [4 /*yield*/, this.beforeUpdate(params, opt)];
465
474
  case 1:
466
475
  object = _c.sent();
467
476
  return [4 /*yield*/, ((_b = this.gateway) === null || _b === void 0 ? void 0 : _b.update(where, object))];
468
477
  case 2:
469
478
  item = _c.sent();
470
- return [4 /*yield*/, this.afterUpdate(item, this.getGateways())];
479
+ return [4 /*yield*/, this.afterUpdate(item, opt)];
471
480
  case 3:
472
481
  result = _c.sent();
473
482
  return [2 /*return*/, this.success(result, result.length > 0 ? api_helpers_1.OP_RESULT_CODES.OK : api_helpers_1.OP_RESULT_CODES.NOT_FOUND)];
474
483
  }
475
484
  });
476
485
  }); },
477
- hasTransaction: false,
486
+ hasTransaction: true,
478
487
  doingWhat: (_c = (_b = (_a = this.doingWhat) === null || _a === void 0 ? void 0 : _a.update) !== null && _b !== void 0 ? _b : this.name) !== null && _c !== void 0 ? _c : 'updating an item',
479
488
  })];
480
489
  });
@@ -489,7 +498,7 @@ var BaseCore = /** @class */ (function () {
489
498
  args: args,
490
499
  validate: this.validators.updateMany,
491
500
  accessRights: [ACCESS_RIGHTS.UPDATE],
492
- action: function (args) { return __awaiter(_this, void 0, void 0, function () {
501
+ action: function (args, opt) { return __awaiter(_this, void 0, void 0, function () {
493
502
  var params, object, items, result;
494
503
  var _a;
495
504
  return __generator(this, function (_b) {
@@ -497,20 +506,20 @@ var BaseCore = /** @class */ (function () {
497
506
  case 0:
498
507
  params = (args || {}).params;
499
508
  this.logger.log("Requesting update of an item for " + this.name + ":", args);
500
- return [4 /*yield*/, this.beforeUpdateMany(params, this.getGateways())];
509
+ return [4 /*yield*/, this.beforeUpdateMany(params, opt)];
501
510
  case 1:
502
511
  object = _b.sent();
503
512
  return [4 /*yield*/, ((_a = this.gateway) === null || _a === void 0 ? void 0 : _a.updateMany(object))];
504
513
  case 2:
505
514
  items = _b.sent();
506
- return [4 /*yield*/, this.afterUpdateMany(items, this.getGateways())];
515
+ return [4 /*yield*/, this.afterUpdateMany(items, opt)];
507
516
  case 3:
508
517
  result = _b.sent();
509
518
  return [2 /*return*/, this.success(result)];
510
519
  }
511
520
  });
512
521
  }); },
513
- hasTransaction: false,
522
+ hasTransaction: true,
514
523
  doingWhat: (_c = (_b = (_a = this.doingWhat) === null || _a === void 0 ? void 0 : _a.updateMany) !== null && _b !== void 0 ? _b : this.name) !== null && _c !== void 0 ? _c : 'updating multiple items',
515
524
  })];
516
525
  });
@@ -525,7 +534,7 @@ var BaseCore = /** @class */ (function () {
525
534
  args: args,
526
535
  validate: this.validators.set,
527
536
  accessRights: [ACCESS_RIGHTS.CREATE, ACCESS_RIGHTS.UPDATE],
528
- action: function (args) { return __awaiter(_this, void 0, void 0, function () {
537
+ action: function (args, opt /* { setStep, validatedItems, sameRequest } */) { return __awaiter(_this, void 0, void 0, function () {
529
538
  var params, object, items, result;
530
539
  var _a;
531
540
  return __generator(this, function (_b) {
@@ -533,20 +542,20 @@ var BaseCore = /** @class */ (function () {
533
542
  case 0:
534
543
  params = (args || {}).params;
535
544
  this.logger.log("Requesting setting of item(s) for " + this.name + ":", args);
536
- return [4 /*yield*/, this.beforeSet(params, this.getGateways())];
545
+ return [4 /*yield*/, this.beforeSet(params, opt)];
537
546
  case 1:
538
547
  object = _b.sent();
539
548
  return [4 /*yield*/, ((_a = this.gateway) === null || _a === void 0 ? void 0 : _a.set(object))];
540
549
  case 2:
541
550
  items = _b.sent();
542
- return [4 /*yield*/, this.afterSet(items, this.getGateways())];
551
+ return [4 /*yield*/, this.afterSet(items, opt)];
543
552
  case 3:
544
553
  result = _b.sent();
545
554
  return [2 /*return*/, this.success(result)];
546
555
  }
547
556
  });
548
557
  }); },
549
- hasTransaction: false,
558
+ hasTransaction: true,
550
559
  doingWhat: (_c = (_b = (_a = this.doingWhat) === null || _a === void 0 ? void 0 : _a.updateMany) !== null && _b !== void 0 ? _b : this.name) !== null && _c !== void 0 ? _c : 'updating multiple items',
551
560
  })];
552
561
  });
@@ -561,7 +570,7 @@ var BaseCore = /** @class */ (function () {
561
570
  args: args,
562
571
  validate: this.validators.remove,
563
572
  accessRights: [ACCESS_RIGHTS.REMOVE],
564
- action: function (args) { return __awaiter(_this, void 0, void 0, function () {
573
+ action: function (args, opt) { return __awaiter(_this, void 0, void 0, function () {
565
574
  var where, object, items, result;
566
575
  var _a;
567
576
  return __generator(this, function (_b) {
@@ -569,13 +578,13 @@ var BaseCore = /** @class */ (function () {
569
578
  case 0:
570
579
  where = (args || {}).where;
571
580
  this.logger.log("Requesting removal of an item for " + this.name + ":", args);
572
- return [4 /*yield*/, this.beforeRemove(where, this.getGateways())];
581
+ return [4 /*yield*/, this.beforeRemove(where, opt)];
573
582
  case 1:
574
583
  object = _b.sent();
575
584
  return [4 /*yield*/, ((_a = this.gateway) === null || _a === void 0 ? void 0 : _a.remove(object))];
576
585
  case 2:
577
586
  items = _b.sent();
578
- return [4 /*yield*/, this.afterRemove(items, this.getGateways())];
587
+ return [4 /*yield*/, this.afterRemove(items, opt)];
579
588
  case 3:
580
589
  result = _b.sent();
581
590
  return [2 /*return*/, this.success(result, result.length > 0 ? api_helpers_1.OP_RESULT_CODES.OK : api_helpers_1.OP_RESULT_CODES.NOT_FOUND)];
@@ -597,7 +606,7 @@ var BaseCore = /** @class */ (function () {
597
606
  args: args,
598
607
  validate: this.validators.removeMany,
599
608
  accessRights: [ACCESS_RIGHTS.REMOVE],
600
- action: function (args) { return __awaiter(_this, void 0, void 0, function () {
609
+ action: function (args, opt) { return __awaiter(_this, void 0, void 0, function () {
601
610
  var where, object, items, result;
602
611
  var _a;
603
612
  return __generator(this, function (_b) {
@@ -605,13 +614,13 @@ var BaseCore = /** @class */ (function () {
605
614
  case 0:
606
615
  where = (args || {}).where;
607
616
  this.logger.log("Requesting removal of multiple items for " + this.name + ":", args);
608
- return [4 /*yield*/, this.beforeRemoveMany(where, this.getGateways())];
617
+ return [4 /*yield*/, this.beforeRemoveMany(where, opt)];
609
618
  case 1:
610
619
  object = _b.sent();
611
620
  return [4 /*yield*/, ((_a = this.gateway) === null || _a === void 0 ? void 0 : _a.remove(object))];
612
621
  case 2:
613
622
  items = _b.sent();
614
- return [4 /*yield*/, this.afterRemoveMany(items, this.getGateways())];
623
+ return [4 /*yield*/, this.afterRemoveMany(items, opt)];
615
624
  case 3:
616
625
  result = _b.sent();
617
626
  return [2 /*return*/, this.success(result, result.length > 0 ? api_helpers_1.OP_RESULT_CODES.OK : api_helpers_1.OP_RESULT_CODES.NOT_FOUND)];
@@ -1,4 +1,5 @@
1
1
  import { BaseGatewayInterface, ListArgsInterface } from './interfaces';
2
+ import { BaseCore } from '.';
2
3
  declare class BaseGateway {
3
4
  protected config: BaseGatewayInterface;
4
5
  protected loader: any;
@@ -12,7 +13,9 @@ declare class BaseGateway {
12
13
  constructor(props: BaseGatewayInterface);
13
14
  getDb(): import("./database").Database;
14
15
  getBuilder(): any;
15
- getIdField(): string;
16
+ getIdField(): any;
17
+ getCore(): BaseCore;
18
+ setCore(core: BaseCore): void;
16
19
  get(id: any): Promise<any>;
17
20
  getMany(ids: any[]): Promise<any>;
18
21
  list(args?: ListArgsInterface): Promise<any>;
@@ -100,6 +100,12 @@ var BaseGateway = /** @class */ (function () {
100
100
  BaseGateway.prototype.getIdField = function () {
101
101
  return this.config.idField || ID_FIELD;
102
102
  };
103
+ BaseGateway.prototype.getCore = function () {
104
+ return this.config.core;
105
+ };
106
+ BaseGateway.prototype.setCore = function (core) {
107
+ this.config.core = core;
108
+ };
103
109
  BaseGateway.prototype.get = function (id) {
104
110
  return __awaiter(this, void 0, void 0, function () {
105
111
  return __generator(this, function (_a) {
@@ -218,6 +224,7 @@ var BaseGateway = /** @class */ (function () {
218
224
  BaseGateway.prototype.updateMany = function (params) {
219
225
  return __awaiter(this, void 0, void 0, function () {
220
226
  var results, idx, len, item, items;
227
+ var _this = this;
221
228
  return __generator(this, function (_a) {
222
229
  switch (_a.label) {
223
230
  case 0:
@@ -238,7 +245,11 @@ var BaseGateway = /** @class */ (function () {
238
245
  case 3:
239
246
  ++idx;
240
247
  return [3 /*break*/, 1];
241
- case 4: return [2 /*return*/, results];
248
+ case 4:
249
+ if (results.length > 0 && this.config.noCache !== true) {
250
+ results.forEach(function (item) { return _this.loader.clear(item[_this.getIdField()]); });
251
+ }
252
+ return [2 /*return*/, results];
242
253
  }
243
254
  });
244
255
  });
@@ -0,0 +1,20 @@
1
+ export declare const buildDefaultGatewayProps: (args: any) => {
2
+ filter: (query: any, params: any) => any;
3
+ keyPrefix: any;
4
+ context: any;
5
+ buildKey: any;
6
+ table: any;
7
+ idField: any;
8
+ setFields: any;
9
+ readAll: boolean;
10
+ redisClient: any;
11
+ cacheTtl: any;
12
+ noCache: boolean;
13
+ idGenerator: () => string;
14
+ insertFormatter: (args?: any) => any;
15
+ updateFormatter: (args?: any) => any;
16
+ updateFilter: (query: any, params: any) => void;
17
+ removeFormatter: () => any;
18
+ removeFilter: (query: any, params: any) => void;
19
+ returnFields: any[];
20
+ };
@@ -0,0 +1,86 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.buildDefaultGatewayProps = void 0;
7
+ var uuid_1 = require("uuid");
8
+ var dayjs_1 = __importDefault(require("dayjs"));
9
+ var lodash_1 = require("lodash");
10
+ var constants_1 = __importDefault(require("./constants"));
11
+ var FIELDS = constants_1.default.FIELDS, STATUSES = constants_1.default.STATUSES;
12
+ var buildDefaultGatewayProps = function (args) {
13
+ var config = args.config, tableName = args.tableName, filter = args.filter, updateFilter = args.updateFilter, hasStatus = args.hasStatus, hasRemovedAt = args.hasRemovedAt, hasRemovedAtStr = args.hasRemovedAtStr, setFields = args.setFields, idField = args.idField, activeStatuses = args.activeStatuses, redisClient = args.redisClient, context = args.context, buildKey = args.buildKey;
14
+ return {
15
+ filter: function (query, params) {
16
+ if (hasStatus === undefined || hasStatus === true) {
17
+ query.whereIn(FIELDS.STATUS, activeStatuses);
18
+ }
19
+ else if (hasRemovedAt === undefined || hasRemovedAt === true) {
20
+ query.whereNull(FIELDS.REMOVED_AT);
21
+ }
22
+ if (typeof filter === 'function') {
23
+ filter(query, params);
24
+ }
25
+ return query;
26
+ },
27
+ keyPrefix: tableName,
28
+ context: context,
29
+ buildKey: buildKey,
30
+ table: tableName,
31
+ idField: idField || FIELDS.ID,
32
+ setFields: setFields,
33
+ readAll: false,
34
+ redisClient: redisClient,
35
+ cacheTtl: config.cacheTtl,
36
+ noCache: false,
37
+ idGenerator: function () {
38
+ var id = uuid_1.v4();
39
+ return id;
40
+ },
41
+ insertFormatter: function (args) {
42
+ return args;
43
+ },
44
+ updateFormatter: function (args) {
45
+ return args;
46
+ },
47
+ updateFilter: function (query, params) {
48
+ var id = (params || {}).id;
49
+ if (id) {
50
+ query.whereIn(FIELDS.ID, lodash_1.castArray(id));
51
+ }
52
+ if (typeof updateFilter === 'function') {
53
+ updateFilter(query, params);
54
+ }
55
+ },
56
+ removeFormatter: function () {
57
+ var removalTime = dayjs_1.default();
58
+ var removedAt = removalTime.toDate();
59
+ var obj = {
60
+ removedAt: removedAt,
61
+ };
62
+ if (hasRemovedAtStr === undefined || hasRemovedAtStr === true) {
63
+ obj[FIELDS.REMOVED_AT_STR] = removalTime.format('YYYYMMDDTHHmmssZ');
64
+ }
65
+ if (hasStatus === undefined || hasStatus === true) {
66
+ obj[FIELDS.STATUS] = STATUSES.REMOVED;
67
+ }
68
+ return obj;
69
+ },
70
+ removeFilter: function (query, params) {
71
+ var arr = [];
72
+ if (Array.isArray(params)) {
73
+ arr.push.apply(arr, params);
74
+ }
75
+ else {
76
+ arr.push(params);
77
+ }
78
+ query = query.whereIn(FIELDS.ID, arr.map(function (item) { return item[FIELDS.ID]; }));
79
+ if (hasStatus === undefined || hasStatus === true) {
80
+ query.where(FIELDS.STATUS, '!=', STATUSES.REMOVED);
81
+ }
82
+ },
83
+ returnFields: [FIELDS.ID],
84
+ };
85
+ };
86
+ exports.buildDefaultGatewayProps = buildDefaultGatewayProps;
@@ -1,29 +1,2 @@
1
- declare const constants: {
2
- ID_FIELD: string;
3
- FIELDS: {
4
- STATUS: string;
5
- VERSION: string;
6
- CREATED_BY: string;
7
- UPDATED_BY: string;
8
- REMOVED_BY: string;
9
- CREATED_AT: string;
10
- UPDATED_AT: string;
11
- REMOVED_AT: string;
12
- REMOVED_AT_STR: string;
13
- };
14
- STATUSES: {
15
- TEST: number;
16
- ACTIVE: number;
17
- DRAFT: number;
18
- DISABLED: number;
19
- REMOVED: number;
20
- };
21
- ACCESS_RIGHTS: {
22
- LIST: number;
23
- GET: number;
24
- CREATE: number;
25
- UPDATE: number;
26
- REMOVE: number;
27
- };
28
- };
1
+ declare const constants: any;
29
2
  export default constants;
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  var constants = {
4
4
  ID_FIELD: 'id',
5
5
  FIELDS: {
6
+ ID: 'id',
6
7
  STATUS: 'status',
7
8
  VERSION: 'version',
8
9
  CREATED_BY: 'created_by',
@@ -17,8 +18,10 @@ var constants = {
17
18
  TEST: 50,
18
19
  ACTIVE: 100,
19
20
  DRAFT: 200,
20
- DISABLED: 300,
21
- REMOVED: 1000,
21
+ PENDING: 300,
22
+ BLOCKED: 1000,
23
+ DISABLED: 5000,
24
+ REMOVED: 10000,
22
25
  },
23
26
  ACCESS_RIGHTS: {
24
27
  LIST: 1,
package/build/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import constants from './constants';
2
- export { CacheInterface, LoaderInterface, BaseGatewayInterface, ListArgsInterface, SortItemInterface, PaginationInterface, BaseCoreInterface, DoingWhatInterface, CoreActionInterface, ApiContextInterface, DbFieldAddDefaultInterface, BuildConfigOptions, DatabaseOptions, DatabaseReadInterface, BuildDefaultResolvers, BaseCoreValidatorsInterface, } from './interfaces';
2
+ export { CacheInterface, LoaderInterface, BaseGatewayInterface, ListArgsInterface, SortItemInterface, PaginationInterface, BaseCoreInterface, BaseCoreDoingWhatInterface, CoreActionInterface, ApiContextInterface, DbFieldAddDefaultInterface, BuildConfigOptions, DatabaseOptions, DatabaseReadInterface, BuildDefaultResolvers, BaseCoreValidatorsInterface, } from './interfaces';
3
3
  export { buildConfig } from './configBulder';
4
4
  export { Database } from './database';
5
5
  export { dbCleanTable, dbListTables, dbClean, dbWipe, dbReset, dbTransformSeedsToObject, dbRunMigrations, } from './dbHelpers';
@@ -11,8 +11,10 @@ export { checkArray, createErrorOnCheckError } from './checkItHelpers';
11
11
  export { DataCache } from './dataCache';
12
12
  export { BaseGateway } from './baseGateway';
13
13
  export { BaseCore } from './baseCore';
14
- export { createApiContext } from './apiContext';
14
+ export { createApiContext, createContextDefault } from './apiContext';
15
15
  export { BaseController } from './baseController';
16
16
  export { dbFieldAddDefaults } from './dbTableHelpers';
17
17
  export { buildDefaultResolvers } from './resolversHelpers';
18
+ export { createUserToken, verifyUserToken } from './userToken';
18
19
  export { constants };
20
+ export { buildDefaultGatewayProps } from './baseGatewayHelpers';
package/build/index.js CHANGED
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.constants = exports.buildDefaultResolvers = exports.dbFieldAddDefaults = exports.BaseController = exports.createApiContext = exports.BaseCore = exports.BaseGateway = exports.DataCache = exports.createErrorOnCheckError = exports.checkArray = exports.createRedisClient = exports.buildKnexConfig = exports.dbSeed = exports.DbMigratorAndSeeder = exports.dbRunMigrations = exports.dbTransformSeedsToObject = exports.dbReset = exports.dbWipe = exports.dbClean = exports.dbListTables = exports.dbCleanTable = exports.Database = exports.buildConfig = void 0;
6
+ exports.buildDefaultGatewayProps = exports.constants = exports.verifyUserToken = exports.createUserToken = exports.buildDefaultResolvers = exports.dbFieldAddDefaults = exports.BaseController = exports.createContextDefault = exports.createApiContext = exports.BaseCore = exports.BaseGateway = exports.DataCache = exports.createErrorOnCheckError = exports.checkArray = exports.createRedisClient = exports.buildKnexConfig = exports.dbSeed = exports.DbMigratorAndSeeder = exports.dbRunMigrations = exports.dbTransformSeedsToObject = exports.dbReset = exports.dbWipe = exports.dbClean = exports.dbListTables = exports.dbCleanTable = exports.Database = exports.buildConfig = void 0;
7
7
  var constants_1 = __importDefault(require("./constants"));
8
8
  exports.constants = constants_1.default;
9
9
  var configBulder_1 = require("./configBulder");
@@ -37,9 +37,15 @@ var baseCore_1 = require("./baseCore");
37
37
  Object.defineProperty(exports, "BaseCore", { enumerable: true, get: function () { return baseCore_1.BaseCore; } });
38
38
  var apiContext_1 = require("./apiContext");
39
39
  Object.defineProperty(exports, "createApiContext", { enumerable: true, get: function () { return apiContext_1.createApiContext; } });
40
+ Object.defineProperty(exports, "createContextDefault", { enumerable: true, get: function () { return apiContext_1.createContextDefault; } });
40
41
  var baseController_1 = require("./baseController");
41
42
  Object.defineProperty(exports, "BaseController", { enumerable: true, get: function () { return baseController_1.BaseController; } });
42
43
  var dbTableHelpers_1 = require("./dbTableHelpers");
43
44
  Object.defineProperty(exports, "dbFieldAddDefaults", { enumerable: true, get: function () { return dbTableHelpers_1.dbFieldAddDefaults; } });
44
45
  var resolversHelpers_1 = require("./resolversHelpers");
45
46
  Object.defineProperty(exports, "buildDefaultResolvers", { enumerable: true, get: function () { return resolversHelpers_1.buildDefaultResolvers; } });
47
+ var userToken_1 = require("./userToken");
48
+ Object.defineProperty(exports, "createUserToken", { enumerable: true, get: function () { return userToken_1.createUserToken; } });
49
+ Object.defineProperty(exports, "verifyUserToken", { enumerable: true, get: function () { return userToken_1.verifyUserToken; } });
50
+ var baseGatewayHelpers_1 = require("./baseGatewayHelpers");
51
+ Object.defineProperty(exports, "buildDefaultGatewayProps", { enumerable: true, get: function () { return baseGatewayHelpers_1.buildDefaultGatewayProps; } });
@@ -0,0 +1,34 @@
1
+ import { BaseCore } from '..';
2
+ export interface BaseCoreActionsInterface {
3
+ /**
4
+ * Reference to the core object that processes the request
5
+ */
6
+ core: BaseCore;
7
+ /**
8
+ * Sets current step when processing an action
9
+ * @param str Name of step
10
+ */
11
+ setStep?(str: string): void;
12
+ /**
13
+ * The sameRequest is true when we call a core method when handling the same request (actual for GraphQL resolvers)
14
+ */
15
+ sameRequest?: boolean;
16
+ /**
17
+ * The transaction is active when processing some of actions that configured to open transaction
18
+ */
19
+ hasTransaction?: boolean;
20
+ /**
21
+ * The validatedItems exists after validator execution.
22
+ * It is expected that validator return an array in which second element is some
23
+ * items that were read from data or created otherwise during validation
24
+ */
25
+ validatedItems?: any;
26
+ /**
27
+ * The exception object exists only when exception happened when processing an action
28
+ */
29
+ exception?: any;
30
+ /**
31
+ * Name of action for exception error messages
32
+ */
33
+ doingWhat?: string;
34
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,13 @@
1
+ export interface BaseCoreDoingWhatInterface {
2
+ list: string;
3
+ get: string;
4
+ getMany: string;
5
+ create: string;
6
+ createMany: string;
7
+ update: string;
8
+ updateMany: string;
9
+ set: string;
10
+ remove: string;
11
+ removeMany: string;
12
+ [key: string]: string;
13
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,20 +1,9 @@
1
+ import { BaseCoreActionsInterface } from './BaseCoreActionsInterface';
1
2
  import { LoggerLevels, Logger } from '@sdflc/utils';
2
3
  import { Database } from '../database';
3
4
  import { BaseGateway } from '../baseGateway';
4
5
  import { BaseCoreValidatorsInterface } from './BaseCoreValidatorsInterface';
5
- export interface DoingWhatInterface {
6
- list: string;
7
- get: string;
8
- getMany: string;
9
- create: string;
10
- createMany: string;
11
- update: string;
12
- updateMany: string;
13
- set: string;
14
- remove: string;
15
- removeMany: string;
16
- [key: string]: string;
17
- }
6
+ import { BaseCoreDoingWhatInterface } from './BaseCoreDoingWhatInterface';
18
7
  export interface BaseCoreInterface {
19
8
  db: Database;
20
9
  context?: any;
@@ -24,35 +13,26 @@ export interface BaseCoreInterface {
24
13
  logLevel: LoggerLevels;
25
14
  logger?: Logger;
26
15
  name?: string;
27
- doingWhat?: DoingWhatInterface;
28
- beforeList?(params: any, gateways?: any): any;
29
- beforeCreate?(params: any, gateways?: any): any;
30
- beforeCreateMany?(params: any, gateways?: any): any;
31
- beforeUpdate?(params: any, gateways?: any): any;
32
- beforeUpdateMany?(params: any, gateways?: any): any;
33
- beforeSet?(params: any, gateways?: any): any;
34
- beforeRemove?(params: any, gateways?: any): any;
35
- beforeRemoveMany?(params: any, gateways?: any): any;
36
- afterList?(params: any, gateways?: any): any;
37
- afterCreate?(params: any, gateways?: any): any;
38
- afterCreateMany?(params: any, gateways?: any): any;
39
- afterUpdate?(params: any, gateways?: any): any;
40
- afterUpdateMany?(params: any, gateways?: any): any;
41
- afterSet?(params: any, gateways?: any): any;
42
- afterRemove?(params: any, gateways?: any): any;
43
- afterRemoveMany?(params: any, gateways?: any): any;
44
- validateList?(params: any, gateways?: any): Promise<any[]> | any[];
45
- validateGet?(params: any, gateways?: any): Promise<any[]> | any[];
46
- validateGetMany?(params: any, gateways?: any): Promise<any[]> | any[];
47
- validateCreate?(params: any, gateways?: any): Promise<any[]> | any[];
48
- validateCreateMany?(params: any, gateways?: any): Promise<any[]> | any[];
49
- validateUpdate?(params: any, gateways?: any): Promise<any[]> | any[];
50
- validateUpdateMany?(params: any, gateways?: any): Promise<any[]> | any[];
51
- validateSet?(params: any, gateways?: any): Promise<any[]> | any[];
52
- validateRemove?(params: any, gateways?: any): Promise<any[]> | any[];
53
- validateRemoveMany?(params: any, gateways?: any): Promise<any[]> | any[];
54
- validators?: BaseCoreValidatorsInterface;
55
- authenticate?(params: any): Promise<any[]> | any[];
56
- doAuth: boolean;
57
16
  requestId: string;
17
+ doAuth: boolean;
18
+ doingWhat?: BaseCoreDoingWhatInterface;
19
+ beforeList?(params: any, opt?: BaseCoreActionsInterface): any;
20
+ beforeCreate?(params: any, opt?: BaseCoreActionsInterface): any;
21
+ beforeCreateMany?(params: any, opt?: BaseCoreActionsInterface): any;
22
+ beforeUpdate?(params: any, opt?: BaseCoreActionsInterface): any;
23
+ beforeUpdateMany?(params: any, opt?: BaseCoreActionsInterface): any;
24
+ beforeSet?(params: any, opt?: any): BaseCoreActionsInterface;
25
+ beforeRemove?(params: any, opt?: BaseCoreActionsInterface): any;
26
+ beforeRemoveMany?(params: any, opt?: BaseCoreActionsInterface): any;
27
+ afterList?(params: any, opt?: BaseCoreActionsInterface): any;
28
+ afterCreate?(params: any, opt?: BaseCoreActionsInterface): any;
29
+ afterCreateMany?(params: any, opt?: BaseCoreActionsInterface): any;
30
+ afterUpdate?(params: any, opt?: BaseCoreActionsInterface): any;
31
+ afterUpdateMany?(params: any, opt?: BaseCoreActionsInterface): any;
32
+ afterSet?(params: any, opt?: BaseCoreActionsInterface): any;
33
+ afterRemove?(params: any, opt?: BaseCoreActionsInterface): any;
34
+ afterRemoveMany?(params: any, opt?: BaseCoreActionsInterface): any;
35
+ onException?(params: any, opt?: BaseCoreActionsInterface): any;
36
+ validators?: BaseCoreValidatorsInterface;
37
+ authenticate?(params: any, opt?: BaseCoreActionsInterface): Promise<any[]> | any[];
58
38
  }
@@ -1,12 +1,13 @@
1
+ import { BaseCoreActionsInterface } from './BaseCoreActionsInterface';
1
2
  export interface BaseCoreValidatorsInterface {
2
- list?(params: any, gateways?: any): Promise<any[]> | any[];
3
- get?(params: any, gateways?: any): Promise<any[]> | any[];
4
- getMany?(params: any, gateways?: any): Promise<any[]> | any[];
5
- create?(params: any, gateways?: any): Promise<any[]> | any[];
6
- createMany?(params: any, gateways?: any): Promise<any[]> | any[];
7
- update?(params: any, gateways?: any): Promise<any[]> | any[];
8
- updateMany?(params: any, gateways?: any): Promise<any[]> | any[];
9
- set?(params: any, gateways?: any): Promise<any[]> | any[];
10
- remove?(params: any, gateways?: any): Promise<any[]> | any[];
11
- removeMany?(params: any, gateways?: any): Promise<any[]> | any[];
3
+ list?(params: any, opt?: BaseCoreActionsInterface): Promise<any[]> | any[];
4
+ get?(params: any, opt?: BaseCoreActionsInterface): Promise<any[]> | any[];
5
+ getMany?(params: any, opt?: BaseCoreActionsInterface): Promise<any[]> | any[];
6
+ create?(params: any, opt?: BaseCoreActionsInterface): Promise<any[]> | any[];
7
+ createMany?(params: any, opt?: BaseCoreActionsInterface): Promise<any[]> | any[];
8
+ update?(params: any, opt?: BaseCoreActionsInterface): Promise<any[]> | any[];
9
+ updateMany?(params: any, opt?: BaseCoreActionsInterface): Promise<any[]> | any[];
10
+ set?(params: any, opt?: BaseCoreActionsInterface): Promise<any[]> | any[];
11
+ remove?(params: any, opt?: BaseCoreActionsInterface): Promise<any[]> | any[];
12
+ removeMany?(params: any, opt?: BaseCoreActionsInterface): Promise<any[]> | any[];
12
13
  }
@@ -1,9 +1,11 @@
1
1
  import { LoggerLevels, Logger } from '@sdflc/utils';
2
+ import { BaseCore } from '../baseCore';
2
3
  import { Database } from '../database';
3
4
  import { LoaderInterface } from './LoaderInterface';
4
5
  import { SortItemInterface } from './SortItemInterface';
5
6
  export interface BaseGatewayInterface {
6
7
  db: Database;
8
+ core: BaseCore;
7
9
  table?: string;
8
10
  idField?: string;
9
11
  setFields?: string[] | string;
@@ -2,7 +2,7 @@ export interface CoreActionInterface {
2
2
  args: any;
3
3
  doAuth?: boolean;
4
4
  accessRights?: any[];
5
- validate?(args?: any, gateways?: any): Promise<any[]> | any[];
5
+ validate?(args?: any, gateways?: any, opt?: any): Promise<any[]> | any[];
6
6
  action(args?: any, opt?: any): any;
7
7
  hasTransaction: boolean;
8
8
  doingWhat: string;
@@ -0,0 +1,14 @@
1
+ import { UserTokenParams } from './UserTokenParams';
2
+ export interface CreateUserTokenArgs {
3
+ params: UserTokenParams;
4
+ secret: string;
5
+ algorithm?: any;
6
+ audience?: string | string[];
7
+ issuer?: string;
8
+ jwtid?: string;
9
+ subject?: string;
10
+ noTimestamp?: boolean;
11
+ header?: any;
12
+ keyid?: any;
13
+ expiresIn?: number;
14
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,7 @@
1
+ export interface UserTokenParams {
2
+ spaceId: string;
3
+ accountId: string;
4
+ roleId: string;
5
+ userId: string;
6
+ [tokenProp: string]: string;
7
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,14 @@
1
+ export interface VerifyUserTokenArgs {
2
+ token: string;
3
+ secret: string;
4
+ algorithms?: any;
5
+ audience?: string | string[];
6
+ issuer?: string | string[];
7
+ ignoreExpiration?: boolean;
8
+ ignoreNotBefore?: boolean;
9
+ subject?: string;
10
+ clockTolerance?: number;
11
+ maxAge?: number;
12
+ clockTimestamp?: number;
13
+ nonce?: string;
14
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -4,7 +4,7 @@ export { BaseGatewayInterface } from './BaseGatewayInterface';
4
4
  export { ListArgsInterface } from './ListArgsInterface';
5
5
  export { SortItemInterface } from './SortItemInterface';
6
6
  export { PaginationInterface } from './PaginationInterface';
7
- export { BaseCoreInterface, DoingWhatInterface } from './BaseCoreInterface';
7
+ export { BaseCoreInterface } from './BaseCoreInterface';
8
8
  export { CoreActionInterface } from './CoreActionInterface';
9
9
  export { ApiContextInterface } from './ApiContextInterface';
10
10
  export { DbFieldAddDefaultInterface } from './DbFieldAddDefaultInterface';
@@ -13,3 +13,8 @@ export { DatabaseOptions } from './DatabaseOptions';
13
13
  export { DatabaseReadInterface } from './DatabaseReadInterface';
14
14
  export { BuildDefaultResolvers } from './BuildDefaultResolversOptions';
15
15
  export { BaseCoreValidatorsInterface } from './BaseCoreValidatorsInterface';
16
+ export { UserTokenParams } from './UserTokenParams';
17
+ export { CreateUserTokenArgs } from './CreateUserTokenArgs';
18
+ export { VerifyUserTokenArgs } from './VerifyUserTokenArgs';
19
+ export { BaseCoreActionsInterface } from './BaseCoreActionsInterface';
20
+ export { BaseCoreDoingWhatInterface } from './BaseCoreDoingWhatInterface';
@@ -0,0 +1,4 @@
1
+ import { OpResult } from '@sdflc/api-helpers';
2
+ import { CreateUserTokenArgs, VerifyUserTokenArgs } from './interfaces';
3
+ export declare const createUserToken: (args: CreateUserTokenArgs) => OpResult;
4
+ export declare const verifyUserToken: (args: VerifyUserTokenArgs) => OpResult;
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.verifyUserToken = exports.createUserToken = void 0;
7
+ var jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
8
+ var api_helpers_1 = require("@sdflc/api-helpers");
9
+ var createUserToken = function (args) {
10
+ var _a = args || {}, params = _a.params, secret = _a.secret, algorithm = _a.algorithm, audience = _a.audience, issuer = _a.issuer, jwtid = _a.jwtid, subject = _a.subject, noTimestamp = _a.noTimestamp, header = _a.header, keyid = _a.keyid, expiresIn = _a.expiresIn;
11
+ if (!args) {
12
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED);
13
+ }
14
+ var token = jsonwebtoken_1.default.sign(params, secret, {
15
+ algorithm: algorithm,
16
+ audience: audience,
17
+ issuer: issuer,
18
+ jwtid: jwtid,
19
+ subject: subject,
20
+ noTimestamp: noTimestamp,
21
+ header: header,
22
+ keyid: keyid,
23
+ expiresIn: expiresIn && !isNaN(expiresIn) ? expiresIn : undefined,
24
+ });
25
+ return api_helpers_1.OpResult.ok(token);
26
+ };
27
+ exports.createUserToken = createUserToken;
28
+ var verifyUserToken = function (args) {
29
+ var _a = args || {}, token = _a.token, secret = _a.secret, algorithms = _a.algorithms, audience = _a.audience, issuer = _a.issuer, ignoreExpiration = _a.ignoreExpiration, ignoreNotBefore = _a.ignoreNotBefore, subject = _a.subject, clockTolerance = _a.clockTolerance, maxAge = _a.maxAge, clockTimestamp = _a.clockTimestamp, nonce = _a.nonce;
30
+ if (!args) {
31
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED);
32
+ }
33
+ var obj = jsonwebtoken_1.default.verify(token, secret, {
34
+ algorithms: algorithms,
35
+ audience: audience,
36
+ issuer: issuer,
37
+ ignoreExpiration: ignoreExpiration,
38
+ ignoreNotBefore: ignoreNotBefore,
39
+ subject: subject,
40
+ clockTolerance: clockTolerance,
41
+ maxAge: maxAge,
42
+ clockTimestamp: clockTimestamp,
43
+ nonce: nonce,
44
+ });
45
+ return api_helpers_1.OpResult.ok(obj);
46
+ };
47
+ exports.verifyUserToken = verifyUserToken;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sdflc/backend-helpers",
3
- "version": "1.0.14",
3
+ "version": "1.0.18",
4
4
  "description": "Set of helper functions and classes to simplify building backend apps within @sdflc ecosystem",
5
5
  "main": "build/index.js",
6
6
  "types": "build/index.d.ts",
@@ -27,6 +27,7 @@
27
27
  "@types/bluebird": "^3.5.35",
28
28
  "@types/dotenv-safe": "^8.1.1",
29
29
  "@types/jest": "^26.0.16",
30
+ "@types/jsonwebtoken": "^8.5.8",
30
31
  "@types/lodash": "^4.14.165",
31
32
  "@types/node": "^14.14.10",
32
33
  "@types/redis": "^2.8.29",
@@ -52,7 +53,9 @@
52
53
  "@sdflc/utils": "^1.0.12",
53
54
  "bluebird": "^3.7.2",
54
55
  "dataloader": "^2.0.0",
56
+ "dayjs": "^1.10.7",
55
57
  "dotenv-safe": "^8.2.0",
58
+ "jsonwebtoken": "^8.5.1",
56
59
  "knex": "^0.95.6",
57
60
  "lodash": "^4.17.20",
58
61
  "pg": "^8.6.0",