@sdflc/backend-helpers 1.0.10 → 1.0.15

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.
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, gateways, opt) {
63
63
  return [true, {}];
64
64
  };
65
65
  var defaultValidators = {
@@ -232,7 +232,12 @@ var BaseCore = /** @class */ (function () {
232
232
  case 5:
233
233
  validatedItems = {};
234
234
  if (!(typeof validate === 'function')) return [3 /*break*/, 8];
235
- return [4 /*yield*/, validate(args, this.getGateways())];
235
+ return [4 /*yield*/, validate(args, this.getGateways(), {
236
+ core: this,
237
+ setStep: setStep,
238
+ sameRequest: sameRequest,
239
+ hasTransaction: hasTransaction,
240
+ })];
236
241
  case 6:
237
242
  valideResult = _c.sent();
238
243
  result_1 = valideResult;
@@ -285,20 +290,20 @@ var BaseCore = /** @class */ (function () {
285
290
  args: args,
286
291
  validate: this.validators.list,
287
292
  accessRights: [ACCESS_RIGHTS.LIST],
288
- action: function (args) { return __awaiter(_this, void 0, void 0, function () {
293
+ action: function (args, opt) { return __awaiter(_this, void 0, void 0, function () {
289
294
  var object, items, result;
290
295
  var _a;
291
296
  return __generator(this, function (_b) {
292
297
  switch (_b.label) {
293
298
  case 0:
294
299
  this.logger.log("Requesting a list for " + this.name + ":", args);
295
- return [4 /*yield*/, this.beforeList(args, this.getGateways())];
300
+ return [4 /*yield*/, this.beforeList(args, this.getGateways(), __assign({ core: this }, opt))];
296
301
  case 1:
297
302
  object = _b.sent();
298
303
  return [4 /*yield*/, ((_a = this.gateway) === null || _a === void 0 ? void 0 : _a.list(object))];
299
304
  case 2:
300
305
  items = _b.sent();
301
- return [4 /*yield*/, this.afterList(items, this.getGateways())];
306
+ return [4 /*yield*/, this.afterList(items, this.getGateways(), __assign({ core: this }, opt))];
302
307
  case 3:
303
308
  result = _b.sent();
304
309
  // ON NO DATA RETURN EMPTY CODE
@@ -381,7 +386,7 @@ var BaseCore = /** @class */ (function () {
381
386
  args: args,
382
387
  validate: this.validators.create,
383
388
  accessRights: [ACCESS_RIGHTS.CREATE],
384
- action: function (args) { return __awaiter(_this, void 0, void 0, function () {
389
+ action: function (args, opt) { return __awaiter(_this, void 0, void 0, function () {
385
390
  var params, object, item, result;
386
391
  var _a;
387
392
  return __generator(this, function (_b) {
@@ -389,13 +394,13 @@ var BaseCore = /** @class */ (function () {
389
394
  case 0:
390
395
  params = (args || {}).params;
391
396
  this.logger.log("Requesting creation of an item for " + this.name + ":", args);
392
- return [4 /*yield*/, this.beforeCreate(params, this.getGateways())];
397
+ return [4 /*yield*/, this.beforeCreate(params, this.getGateways(), __assign({ core: this }, opt))];
393
398
  case 1:
394
399
  object = _b.sent();
395
400
  return [4 /*yield*/, ((_a = this.gateway) === null || _a === void 0 ? void 0 : _a.create(object))];
396
401
  case 2:
397
402
  item = _b.sent();
398
- return [4 /*yield*/, this.afterCreate(item, this.getGateways())];
403
+ return [4 /*yield*/, this.afterCreate(item, this.getGateways(), __assign({ core: this }, opt))];
399
404
  case 3:
400
405
  result = _b.sent();
401
406
  return [2 /*return*/, this.success(result)];
@@ -417,7 +422,7 @@ var BaseCore = /** @class */ (function () {
417
422
  args: args,
418
423
  validate: this.validators.createMany,
419
424
  accessRights: [ACCESS_RIGHTS.CREATE],
420
- action: function (args) { return __awaiter(_this, void 0, void 0, function () {
425
+ action: function (args, opt) { return __awaiter(_this, void 0, void 0, function () {
421
426
  var params, objects, items, result;
422
427
  var _a;
423
428
  return __generator(this, function (_b) {
@@ -425,13 +430,13 @@ var BaseCore = /** @class */ (function () {
425
430
  case 0:
426
431
  params = (args || {}).params;
427
432
  this.logger.log("Requesting creation of multiple items for " + this.name + ":", args);
428
- return [4 /*yield*/, this.beforeCreateMany(params, this.getGateways())];
433
+ return [4 /*yield*/, this.beforeCreateMany(params, this.getGateways(), __assign({ core: this }, opt))];
429
434
  case 1:
430
435
  objects = _b.sent();
431
436
  return [4 /*yield*/, ((_a = this.gateway) === null || _a === void 0 ? void 0 : _a.create(objects))];
432
437
  case 2:
433
438
  items = _b.sent();
434
- return [4 /*yield*/, this.afterCreateMany(items, this.getGateways())];
439
+ return [4 /*yield*/, this.afterCreateMany(items, this.getGateways(), __assign({ core: this }, opt))];
435
440
  case 3:
436
441
  result = _b.sent();
437
442
  return [2 /*return*/, this.success(result)];
@@ -453,7 +458,7 @@ var BaseCore = /** @class */ (function () {
453
458
  args: args,
454
459
  validate: this.validators.update,
455
460
  accessRights: [ACCESS_RIGHTS.UPDATE],
456
- action: function (args) { return __awaiter(_this, void 0, void 0, function () {
461
+ action: function (args, opt) { return __awaiter(_this, void 0, void 0, function () {
457
462
  var _a, where, params, object, item, result;
458
463
  var _b;
459
464
  return __generator(this, function (_c) {
@@ -461,13 +466,13 @@ var BaseCore = /** @class */ (function () {
461
466
  case 0:
462
467
  _a = args || {}, where = _a.where, params = _a.params;
463
468
  this.logger.log("Requesting update of an item for " + this.name + ":", args);
464
- return [4 /*yield*/, this.beforeUpdate(params, this.getGateways())];
469
+ return [4 /*yield*/, this.beforeUpdate(params, this.getGateways(), __assign({ core: this }, opt))];
465
470
  case 1:
466
471
  object = _c.sent();
467
472
  return [4 /*yield*/, ((_b = this.gateway) === null || _b === void 0 ? void 0 : _b.update(where, object))];
468
473
  case 2:
469
474
  item = _c.sent();
470
- return [4 /*yield*/, this.afterUpdate(item, this.getGateways())];
475
+ return [4 /*yield*/, this.afterUpdate(item, this.getGateways(), __assign({ core: this }, opt))];
471
476
  case 3:
472
477
  result = _c.sent();
473
478
  return [2 /*return*/, this.success(result, result.length > 0 ? api_helpers_1.OP_RESULT_CODES.OK : api_helpers_1.OP_RESULT_CODES.NOT_FOUND)];
@@ -489,7 +494,7 @@ var BaseCore = /** @class */ (function () {
489
494
  args: args,
490
495
  validate: this.validators.updateMany,
491
496
  accessRights: [ACCESS_RIGHTS.UPDATE],
492
- action: function (args) { return __awaiter(_this, void 0, void 0, function () {
497
+ action: function (args, opt) { return __awaiter(_this, void 0, void 0, function () {
493
498
  var params, object, items, result;
494
499
  var _a;
495
500
  return __generator(this, function (_b) {
@@ -497,13 +502,13 @@ var BaseCore = /** @class */ (function () {
497
502
  case 0:
498
503
  params = (args || {}).params;
499
504
  this.logger.log("Requesting update of an item for " + this.name + ":", args);
500
- return [4 /*yield*/, this.beforeUpdateMany(params, this.getGateways())];
505
+ return [4 /*yield*/, this.beforeUpdateMany(params, this.getGateways(), __assign({ core: this }, opt))];
501
506
  case 1:
502
507
  object = _b.sent();
503
508
  return [4 /*yield*/, ((_a = this.gateway) === null || _a === void 0 ? void 0 : _a.updateMany(object))];
504
509
  case 2:
505
510
  items = _b.sent();
506
- return [4 /*yield*/, this.afterUpdateMany(items, this.getGateways())];
511
+ return [4 /*yield*/, this.afterUpdateMany(items, this.getGateways(), __assign({ core: this }, opt))];
507
512
  case 3:
508
513
  result = _b.sent();
509
514
  return [2 /*return*/, this.success(result)];
@@ -524,8 +529,8 @@ var BaseCore = /** @class */ (function () {
524
529
  return [2 /*return*/, this.runAction({
525
530
  args: args,
526
531
  validate: this.validators.set,
527
- accessRights: [ACCESS_RIGHTS.UPDATE, ACCESS_RIGHTS.UPDATE],
528
- action: function (args) { return __awaiter(_this, void 0, void 0, function () {
532
+ accessRights: [ACCESS_RIGHTS.CREATE, ACCESS_RIGHTS.UPDATE],
533
+ action: function (args, opt /* { setStep, validatedItems, sameRequest } */) { return __awaiter(_this, void 0, void 0, function () {
529
534
  var params, object, items, result;
530
535
  var _a;
531
536
  return __generator(this, function (_b) {
@@ -533,13 +538,13 @@ var BaseCore = /** @class */ (function () {
533
538
  case 0:
534
539
  params = (args || {}).params;
535
540
  this.logger.log("Requesting setting of item(s) for " + this.name + ":", args);
536
- return [4 /*yield*/, this.beforeSet(params, this.getGateways())];
541
+ return [4 /*yield*/, this.beforeSet(params, __assign({ core: this }, opt))];
537
542
  case 1:
538
543
  object = _b.sent();
539
544
  return [4 /*yield*/, ((_a = this.gateway) === null || _a === void 0 ? void 0 : _a.set(object))];
540
545
  case 2:
541
546
  items = _b.sent();
542
- return [4 /*yield*/, this.afterSet(items, this.getGateways())];
547
+ return [4 /*yield*/, this.afterSet(items, __assign({ core: this }, opt))];
543
548
  case 3:
544
549
  result = _b.sent();
545
550
  return [2 /*return*/, this.success(result)];
@@ -561,7 +566,7 @@ var BaseCore = /** @class */ (function () {
561
566
  args: args,
562
567
  validate: this.validators.remove,
563
568
  accessRights: [ACCESS_RIGHTS.REMOVE],
564
- action: function (args) { return __awaiter(_this, void 0, void 0, function () {
569
+ action: function (args, opt) { return __awaiter(_this, void 0, void 0, function () {
565
570
  var where, object, items, result;
566
571
  var _a;
567
572
  return __generator(this, function (_b) {
@@ -569,13 +574,13 @@ var BaseCore = /** @class */ (function () {
569
574
  case 0:
570
575
  where = (args || {}).where;
571
576
  this.logger.log("Requesting removal of an item for " + this.name + ":", args);
572
- return [4 /*yield*/, this.beforeRemove(where, this.getGateways())];
577
+ return [4 /*yield*/, this.beforeRemove(where, this.getGateways(), __assign({ core: this }, opt))];
573
578
  case 1:
574
579
  object = _b.sent();
575
580
  return [4 /*yield*/, ((_a = this.gateway) === null || _a === void 0 ? void 0 : _a.remove(object))];
576
581
  case 2:
577
582
  items = _b.sent();
578
- return [4 /*yield*/, this.afterRemove(items, this.getGateways())];
583
+ return [4 /*yield*/, this.afterRemove(items, this.getGateways(), __assign({ core: this }, opt))];
579
584
  case 3:
580
585
  result = _b.sent();
581
586
  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 +602,7 @@ var BaseCore = /** @class */ (function () {
597
602
  args: args,
598
603
  validate: this.validators.removeMany,
599
604
  accessRights: [ACCESS_RIGHTS.REMOVE],
600
- action: function (args) { return __awaiter(_this, void 0, void 0, function () {
605
+ action: function (args, opt) { return __awaiter(_this, void 0, void 0, function () {
601
606
  var where, object, items, result;
602
607
  var _a;
603
608
  return __generator(this, function (_b) {
@@ -605,13 +610,13 @@ var BaseCore = /** @class */ (function () {
605
610
  case 0:
606
611
  where = (args || {}).where;
607
612
  this.logger.log("Requesting removal of multiple items for " + this.name + ":", args);
608
- return [4 /*yield*/, this.beforeRemoveMany(where, this.getGateways())];
613
+ return [4 /*yield*/, this.beforeRemoveMany(where, this.getGateways(), __assign({ core: this }, opt))];
609
614
  case 1:
610
615
  object = _b.sent();
611
616
  return [4 /*yield*/, ((_a = this.gateway) === null || _a === void 0 ? void 0 : _a.remove(object))];
612
617
  case 2:
613
618
  items = _b.sent();
614
- return [4 /*yield*/, this.afterRemoveMany(items, this.getGateways())];
619
+ return [4 /*yield*/, this.afterRemoveMany(items, this.getGateways(), __assign({ core: this }, opt))];
615
620
  case 3:
616
621
  result = _b.sent();
617
622
  return [2 /*return*/, this.success(result, result.length > 0 ? api_helpers_1.OP_RESULT_CODES.OK : api_helpers_1.OP_RESULT_CODES.NOT_FOUND)];
@@ -19,6 +19,8 @@ declare class BaseGateway {
19
19
  create(args: any): Promise<any>;
20
20
  update(where: any, params: any): Promise<any>;
21
21
  updateMany(params: any): Promise<any[]>;
22
+ increment(where: any, params: any): Promise<any>;
23
+ decrement(where: any, params: any): Promise<any>;
22
24
  /**
23
25
  * Inserts or updates data in the database.
24
26
  * If the element of given array has not empty id field then the record is updated
@@ -53,6 +53,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
53
53
  exports.BaseGateway = void 0;
54
54
  var dataCache_1 = require("./dataCache");
55
55
  var constants_1 = __importDefault(require("./constants"));
56
+ var lodash_1 = require("lodash");
56
57
  var ID_FIELD = constants_1.default.ID_FIELD;
57
58
  var defaultIdGenerator = function () {
58
59
  return undefined;
@@ -65,7 +66,7 @@ var defaultUpdateFormatter = function (args) {
65
66
  };
66
67
  var defaultUpdateRemoveFilter = function (config) { return function (query, params) {
67
68
  var idName = config.idField || ID_FIELD;
68
- return query.where(idName, params[idName]);
69
+ query.where(idName, params[idName]);
69
70
  }; };
70
71
  var BaseGateway = /** @class */ (function () {
71
72
  function BaseGateway(props) {
@@ -232,7 +233,7 @@ var BaseGateway = /** @class */ (function () {
232
233
  return [4 /*yield*/, this.update(item.where, item.params)];
233
234
  case 2:
234
235
  items = _a.sent();
235
- results.push(items);
236
+ results.push.apply(results, items);
236
237
  _a.label = 3;
237
238
  case 3:
238
239
  ++idx;
@@ -242,6 +243,54 @@ var BaseGateway = /** @class */ (function () {
242
243
  });
243
244
  });
244
245
  };
246
+ BaseGateway.prototype.increment = function (where, params) {
247
+ return __awaiter(this, void 0, void 0, function () {
248
+ var object, query, items;
249
+ var _this = this;
250
+ return __generator(this, function (_a) {
251
+ switch (_a.label) {
252
+ case 0: return [4 /*yield*/, this.updateFormatter(params)];
253
+ case 1:
254
+ object = _a.sent();
255
+ query = this.getBuilder().increment(object).returning(this.returnFields);
256
+ return [4 /*yield*/, this.updateFilter(query, where)];
257
+ case 2:
258
+ _a.sent();
259
+ return [4 /*yield*/, query];
260
+ case 3:
261
+ items = _a.sent();
262
+ if (items.length > 0 && this.config.noCache !== true) {
263
+ items.forEach(function (item) { return _this.loader.clear(item[_this.getIdField()]); });
264
+ }
265
+ return [2 /*return*/, items];
266
+ }
267
+ });
268
+ });
269
+ };
270
+ BaseGateway.prototype.decrement = function (where, params) {
271
+ return __awaiter(this, void 0, void 0, function () {
272
+ var object, query, items;
273
+ var _this = this;
274
+ return __generator(this, function (_a) {
275
+ switch (_a.label) {
276
+ case 0: return [4 /*yield*/, this.updateFormatter(params)];
277
+ case 1:
278
+ object = _a.sent();
279
+ query = this.getBuilder().decrement(object).returning(this.returnFields);
280
+ return [4 /*yield*/, this.updateFilter(query, where)];
281
+ case 2:
282
+ _a.sent();
283
+ return [4 /*yield*/, query];
284
+ case 3:
285
+ items = _a.sent();
286
+ if (items.length > 0 && this.config.noCache !== true) {
287
+ items.forEach(function (item) { return _this.loader.clear(item[_this.getIdField()]); });
288
+ }
289
+ return [2 /*return*/, items];
290
+ }
291
+ });
292
+ });
293
+ };
245
294
  /**
246
295
  * Inserts or updates data in the database.
247
296
  * If the element of given array has not empty id field then the record is updated
@@ -251,38 +300,21 @@ var BaseGateway = /** @class */ (function () {
251
300
  */
252
301
  BaseGateway.prototype.set = function (params) {
253
302
  return __awaiter(this, void 0, void 0, function () {
254
- var results, idField, idx, len, item, items, items;
255
- var _a;
256
- return __generator(this, function (_b) {
257
- switch (_b.label) {
303
+ var results, idField, items;
304
+ return __generator(this, function (_a) {
305
+ switch (_a.label) {
258
306
  case 0:
259
- if (!Array.isArray(params)) {
260
- params = [params];
261
- }
262
307
  results = [];
263
308
  idField = this.getIdField();
264
- idx = 0, len = params.length;
265
- _b.label = 1;
309
+ return [4 /*yield*/, this.getBuilder()
310
+ .insert(lodash_1.castArray(params))
311
+ .returning(this.returnFields)
312
+ .onConflict(this.config.setFields || idField)
313
+ .merge()];
266
314
  case 1:
267
- if (!(idx < len)) return [3 /*break*/, 6];
268
- item = params[idx];
269
- if (!(item === null || item === void 0 ? void 0 : item[idField])) return [3 /*break*/, 3];
270
- return [4 /*yield*/, this.update((_a = {},
271
- _a[idField] = item === null || item === void 0 ? void 0 : item[idField],
272
- _a), item)];
273
- case 2:
274
- items = _b.sent();
275
- results.push.apply(results, items);
276
- return [3 /*break*/, 5];
277
- case 3: return [4 /*yield*/, this.create(item)];
278
- case 4:
279
- items = _b.sent();
315
+ items = _a.sent();
280
316
  results.push.apply(results, items);
281
- _b.label = 5;
282
- case 5:
283
- ++idx;
284
- return [3 /*break*/, 1];
285
- case 6: return [2 /*return*/, results];
317
+ return [2 /*return*/, results];
286
318
  }
287
319
  });
288
320
  });
@@ -40,8 +40,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
40
40
  };
41
41
  Object.defineProperty(exports, "__esModule", { value: true });
42
42
  exports.dbRunMigrations = exports.dbTransformSeedsToObject = exports.dbReset = exports.dbWipe = exports.dbClean = exports.dbListTables = exports.dbCleanTable = void 0;
43
- var lodash_1 = require("lodash");
44
43
  var bluebird_1 = __importDefault(require("bluebird"));
44
+ var lodash_1 = require("lodash");
45
45
  var SQLS = {
46
46
  pg: {
47
47
  listTablesSchema: function (appSettings) { return "\n SELECT TABLE_NAME as table_name\n FROM INFORMATION_SCHEMA.TABLES\n WHERE TABLE_SCHEMA = '" + (appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema) + "';\n "; },
@@ -59,16 +59,16 @@ var SQLS = {
59
59
  * @param appSettings settings with db related information
60
60
  */
61
61
  var dbCleanTable = function (table, knexHandle, appSettings) { return __awaiter(void 0, void 0, void 0, function () {
62
- var query, cleanTable;
62
+ var query, cleanTableFilters;
63
63
  var _a;
64
64
  return __generator(this, function (_b) {
65
65
  switch (_b.label) {
66
66
  case 0:
67
67
  query = knexHandle(table).withSchema(appSettings.dbSchema).delete();
68
- cleanTable = (_a = appSettings === null || appSettings === void 0 ? void 0 : appSettings.cleanTable) === null || _a === void 0 ? void 0 : _a[table];
69
- if (cleanTable != undefined) {
70
- if (Array.isArray(cleanTable.where)) {
71
- cleanTable.where.forEach(function (whereItem) {
68
+ cleanTableFilters = (_a = appSettings === null || appSettings === void 0 ? void 0 : appSettings.cleanTableFilters) === null || _a === void 0 ? void 0 : _a[table];
69
+ if (cleanTableFilters != undefined) {
70
+ if (Array.isArray(cleanTableFilters.where)) {
71
+ cleanTableFilters.where.forEach(function (whereItem) {
72
72
  query.where(whereItem.fieldName, whereItem.operand, whereItem.value);
73
73
  });
74
74
  }
@@ -0,0 +1,49 @@
1
+ declare class DbMigratorAndSeeder {
2
+ private knexHandle;
3
+ private config;
4
+ private logger;
5
+ constructor(knexHandle: any, config?: any);
6
+ runMigrations(): Promise<void>;
7
+ /**
8
+ * Go from array of objects which contain keys of object names which have an array value of seeded objects
9
+ * to a single object with keys of object names and arrays of seeded objects
10
+ * ie from [{table1: [], table2: [] }, { table3: [] }]
11
+ * to { table1: [], table2: [], table3: []}
12
+ */
13
+ transformSeedsToObject(generatedSeedArrays: any[]): any;
14
+ /**
15
+ * Drop all tables, run migrations, then seed the tables
16
+ */
17
+ resetDb(): Promise<void>;
18
+ /**
19
+ * Selects all the tables in the schema and drops them.
20
+ * This approach does not work in case we have constraints.
21
+ * TODO: Remove all constraints and then drop tables.
22
+ */
23
+ wipeDb(): Promise<void>;
24
+ /**
25
+ * Removes all the records from provided list of tables
26
+ * @param tablesToClean array of table names
27
+ * @param knexHandle Knex handle object with configured connection to DB
28
+ * @param appSettings settings with db related information
29
+ * @returns promise
30
+ */
31
+ cleanDb(tablesToClean: any[]): Promise<unknown>;
32
+ /**
33
+ * Removes all the records from provided table.
34
+ * If appSettings has cleanTable object with table names then
35
+ * it is used to add extra filters to clear the table to avoid for example users data
36
+ * @param table Name of table from which to remove all the records
37
+ */
38
+ cleanDbTable(table: string): Promise<void>;
39
+ /**
40
+ * Returns a list of tables in db schedm specified in settings
41
+ * @returns arrays of table names in the provided db schema
42
+ */
43
+ listDbTables(): Promise<any>;
44
+ generateSeeds(dirname: string, seedFiles: any): Promise<any>;
45
+ removeSeedsFromDb(seedFiles: any): Promise<unknown>;
46
+ insertRecords(seedGroups: any): Promise<any>;
47
+ runSeeds(dirname: string, seedFiles: any): Promise<any>;
48
+ }
49
+ export { DbMigratorAndSeeder };
@@ -0,0 +1,331 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
11
+ }) : function(o, v) {
12
+ o["default"] = v;
13
+ });
14
+ var __importStar = (this && this.__importStar) || function (mod) {
15
+ if (mod && mod.__esModule) return mod;
16
+ var result = {};
17
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
+ __setModuleDefault(result, mod);
19
+ return result;
20
+ };
21
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
22
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
23
+ return new (P || (P = Promise))(function (resolve, reject) {
24
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
25
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
26
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
27
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
28
+ });
29
+ };
30
+ var __generator = (this && this.__generator) || function (thisArg, body) {
31
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
32
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
33
+ function verb(n) { return function (v) { return step([n, v]); }; }
34
+ function step(op) {
35
+ if (f) throw new TypeError("Generator is already executing.");
36
+ while (_) try {
37
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
38
+ if (y = 0, t) op = [op[0] & 2, t.value];
39
+ switch (op[0]) {
40
+ case 0: case 1: t = op; break;
41
+ case 4: _.label++; return { value: op[1], done: false };
42
+ case 5: _.label++; y = op[1]; op = [0]; continue;
43
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
44
+ default:
45
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
46
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
47
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
48
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
49
+ if (t[2]) _.ops.pop();
50
+ _.trys.pop(); continue;
51
+ }
52
+ op = body.call(thisArg, _);
53
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
54
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
55
+ }
56
+ };
57
+ var __importDefault = (this && this.__importDefault) || function (mod) {
58
+ return (mod && mod.__esModule) ? mod : { "default": mod };
59
+ };
60
+ Object.defineProperty(exports, "__esModule", { value: true });
61
+ exports.DbMigratorAndSeeder = void 0;
62
+ var path_1 = __importDefault(require("path"));
63
+ var bluebird_1 = __importDefault(require("bluebird"));
64
+ var lodash_1 = require("lodash");
65
+ var utils_1 = require("@sdflc/utils");
66
+ var SQLS = {
67
+ pg: {
68
+ listTablesSchema: function (appSettings) { return "\n SELECT TABLE_NAME as table_name\n FROM INFORMATION_SCHEMA.TABLES\n WHERE TABLE_SCHEMA = '" + (appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema) + "';\n "; },
69
+ listTables: function () { return "\n SELECT TABLE_NAME as table_name\n FROM INFORMATION_SCHEMA.TABLES\n "; },
70
+ dropTablesSchema: function (appSettings) { return "\n SELECT 'DROP TABLE IF EXISTS " + (appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema) + ".' || TABLE_NAME || ';' as cmd\n FROM INFORMATION_SCHEMA.TABLES\n WHERE TABLE_SCHEMA = '" + (appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema) + "';\n "; },
71
+ dropTables: function () { return "\n SELECT 'DROP TABLE IF EXISTS ' || TABLE_NAME || ';' as cmd\n FROM INFORMATION_SCHEMA.TABLES';\n "; },
72
+ },
73
+ };
74
+ var DbMigratorAndSeeder = /** @class */ (function () {
75
+ function DbMigratorAndSeeder(knexHandle, config) {
76
+ this.knexHandle = knexHandle;
77
+ this.config = config;
78
+ this.logger = (config === null || config === void 0 ? void 0 : config.logger) instanceof utils_1.Logger ? config.logger : new utils_1.Logger({ level: utils_1.LoggerLevels.LOG });
79
+ }
80
+ DbMigratorAndSeeder.prototype.runMigrations = function () {
81
+ return __awaiter(this, void 0, void 0, function () {
82
+ var result, version;
83
+ return __generator(this, function (_a) {
84
+ switch (_a.label) {
85
+ case 0: return [4 /*yield*/, this.knexHandle.migrate.latest()];
86
+ case 1:
87
+ result = _a.sent();
88
+ if (!(this.config && this.config.runDbSeed && result[1].length > 0)) return [3 /*break*/, 3];
89
+ return [4 /*yield*/, this.knexHandle.seed.run()];
90
+ case 2:
91
+ _a.sent();
92
+ _a.label = 3;
93
+ case 3:
94
+ this.logger.log("Ran " + result[1].length + " migration(s)");
95
+ version = this.knexHandle.migrate.currentVersion();
96
+ this.logger.log("Current version of database: " + version);
97
+ return [2 /*return*/];
98
+ }
99
+ });
100
+ });
101
+ };
102
+ /**
103
+ * Go from array of objects which contain keys of object names which have an array value of seeded objects
104
+ * to a single object with keys of object names and arrays of seeded objects
105
+ * ie from [{table1: [], table2: [] }, { table3: [] }]
106
+ * to { table1: [], table2: [], table3: []}
107
+ */
108
+ DbMigratorAndSeeder.prototype.transformSeedsToObject = function (generatedSeedArrays) {
109
+ return lodash_1.reduce(generatedSeedArrays, function (acc, cur) {
110
+ for (var key in cur) {
111
+ acc[key] = cur[key];
112
+ }
113
+ return acc;
114
+ }, {});
115
+ };
116
+ /**
117
+ * Drop all tables, run migrations, then seed the tables
118
+ */
119
+ DbMigratorAndSeeder.prototype.resetDb = function () {
120
+ return __awaiter(this, void 0, void 0, function () {
121
+ var ex_1;
122
+ return __generator(this, function (_a) {
123
+ switch (_a.label) {
124
+ case 0:
125
+ _a.trys.push([0, 3, , 4]);
126
+ return [4 /*yield*/, this.wipeDb()];
127
+ case 1:
128
+ _a.sent();
129
+ return [4 /*yield*/, this.runMigrations()];
130
+ case 2:
131
+ _a.sent();
132
+ return [3 /*break*/, 4];
133
+ case 3:
134
+ ex_1 = _a.sent();
135
+ this.logger.error('An exception has occurred on resetting database: ', ex_1);
136
+ return [3 /*break*/, 4];
137
+ case 4: return [2 /*return*/];
138
+ }
139
+ });
140
+ });
141
+ };
142
+ /**
143
+ * Selects all the tables in the schema and drops them.
144
+ * This approach does not work in case we have constraints.
145
+ * TODO: Remove all constraints and then drop tables.
146
+ */
147
+ DbMigratorAndSeeder.prototype.wipeDb = function () {
148
+ return __awaiter(this, void 0, void 0, function () {
149
+ var query, result, commands;
150
+ var _this = this;
151
+ return __generator(this, function (_a) {
152
+ switch (_a.label) {
153
+ case 0:
154
+ query = this.config.dbSchema
155
+ ? SQLS[this.config.dbType].dropTablesSchema(this.config)
156
+ : SQLS[this.config.dbType].dropTables(this.config);
157
+ return [4 /*yield*/, this.knexHandle.raw(query)];
158
+ case 1:
159
+ result = _a.sent();
160
+ commands = result.rows.map(function (r) { return r.cmd; });
161
+ bluebird_1.default.each(commands, function (cmd) { return _this.knexHandle.raw(cmd); });
162
+ return [2 /*return*/];
163
+ }
164
+ });
165
+ });
166
+ };
167
+ /**
168
+ * Removes all the records from provided list of tables
169
+ * @param tablesToClean array of table names
170
+ * @param knexHandle Knex handle object with configured connection to DB
171
+ * @param appSettings settings with db related information
172
+ * @returns promise
173
+ */
174
+ DbMigratorAndSeeder.prototype.cleanDb = function (tablesToClean) {
175
+ return __awaiter(this, void 0, void 0, function () {
176
+ var idx, len;
177
+ return __generator(this, function (_a) {
178
+ switch (_a.label) {
179
+ case 0:
180
+ idx = 0, len = tablesToClean.length;
181
+ _a.label = 1;
182
+ case 1:
183
+ if (!(idx < len)) return [3 /*break*/, 4];
184
+ return [4 /*yield*/, this.cleanDbTable(tablesToClean[idx])];
185
+ case 2:
186
+ _a.sent();
187
+ _a.label = 3;
188
+ case 3:
189
+ ++idx;
190
+ return [3 /*break*/, 1];
191
+ case 4: return [2 /*return*/, new bluebird_1.default(function (resolve) {
192
+ resolve(tablesToClean);
193
+ })];
194
+ }
195
+ });
196
+ });
197
+ };
198
+ /**
199
+ * Removes all the records from provided table.
200
+ * If appSettings has cleanTable object with table names then
201
+ * it is used to add extra filters to clear the table to avoid for example users data
202
+ * @param table Name of table from which to remove all the records
203
+ */
204
+ DbMigratorAndSeeder.prototype.cleanDbTable = function (table) {
205
+ var _a, _b;
206
+ return __awaiter(this, void 0, void 0, function () {
207
+ var query, cleanTableFilters;
208
+ return __generator(this, function (_c) {
209
+ switch (_c.label) {
210
+ case 0:
211
+ query = this.knexHandle(table).withSchema(this.config.dbSchema).delete();
212
+ cleanTableFilters = (_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.cleanTableFilters) === null || _b === void 0 ? void 0 : _b[table];
213
+ if (cleanTableFilters != undefined) {
214
+ if (Array.isArray(cleanTableFilters.where)) {
215
+ cleanTableFilters.where.forEach(function (whereItem) {
216
+ if (whereItem.fieldName) {
217
+ query.where(whereItem.fieldName, whereItem.operand, whereItem.value);
218
+ }
219
+ });
220
+ }
221
+ }
222
+ return [4 /*yield*/, query];
223
+ case 1:
224
+ _c.sent();
225
+ return [2 /*return*/];
226
+ }
227
+ });
228
+ });
229
+ };
230
+ /**
231
+ * Returns a list of tables in db schedm specified in settings
232
+ * @returns arrays of table names in the provided db schema
233
+ */
234
+ DbMigratorAndSeeder.prototype.listDbTables = function () {
235
+ var _a, _b;
236
+ return __awaiter(this, void 0, void 0, function () {
237
+ var skipTables, query, tables;
238
+ return __generator(this, function (_c) {
239
+ switch (_c.label) {
240
+ case 0:
241
+ skipTables = (_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.skipTables) !== null && _b !== void 0 ? _b : [];
242
+ query = this.config.dbSchema
243
+ ? SQLS[this.config.dbType].listTablesSchema(this.config)
244
+ : SQLS[this.config.dbType].listTables(this.config);
245
+ return [4 /*yield*/, this.knexHandle.raw(query)];
246
+ case 1:
247
+ tables = _c.sent();
248
+ return [2 /*return*/, (tables.rows || [])
249
+ .map(function (row) { return row.table_name; })
250
+ .filter(function (table) { return skipTables.indexOf(table) === -1; })];
251
+ }
252
+ });
253
+ });
254
+ };
255
+ DbMigratorAndSeeder.prototype.generateSeeds = function (dirname, seedFiles) {
256
+ return __awaiter(this, void 0, void 0, function () {
257
+ var seedGroups, seedFileNames, seedFnExports, seedFns, seedFnsMap, i, seedFileName;
258
+ return __generator(this, function (_a) {
259
+ switch (_a.label) {
260
+ case 0:
261
+ seedGroups = [];
262
+ seedFileNames = lodash_1.flatten(seedFiles);
263
+ return [4 /*yield*/, Promise.all(lodash_1.map(seedFileNames, function (filename) { return Promise.resolve().then(function () { return __importStar(require(path_1.default.join(dirname, "./objects/" + filename + ".js"))); }); }))];
264
+ case 1:
265
+ seedFnExports = _a.sent();
266
+ seedFns = lodash_1.map(seedFnExports, 'default');
267
+ seedFnsMap = {};
268
+ for (i = 0; i < seedFileNames.length; i++) {
269
+ seedFileName = seedFileNames[i];
270
+ seedFnsMap[seedFileName] = seedFns[i];
271
+ }
272
+ seedFiles.reduce(function (seeds, fileGroup) {
273
+ seedGroups = seedGroups.concat(fileGroup.reduce(function (group, filename) {
274
+ var _a;
275
+ var seedFn = seedFnsMap[filename];
276
+ var seed = seedFn(seeds);
277
+ var filenameCamel = lodash_1.camelCase(filename);
278
+ seeds[filenameCamel] = seed;
279
+ return Object.assign((_a = {}, _a[filenameCamel] = seed, _a), group);
280
+ }, {}));
281
+ return seeds;
282
+ }, {});
283
+ return [2 /*return*/, seedGroups];
284
+ }
285
+ });
286
+ });
287
+ };
288
+ DbMigratorAndSeeder.prototype.removeSeedsFromDb = function (seedFiles) {
289
+ var tablesToReset = lodash_1.flatten(seedFiles).reverse();
290
+ this.logger.log('Deleting records from tables: ', tablesToReset);
291
+ return this.cleanDb(tablesToReset);
292
+ };
293
+ DbMigratorAndSeeder.prototype.insertRecords = function (seedGroups) {
294
+ return __awaiter(this, void 0, void 0, function () {
295
+ var _this = this;
296
+ return __generator(this, function (_a) {
297
+ this.logger.log('Inserting seeds records into tables...');
298
+ return [2 /*return*/, seedGroups.reduce(function (previousGroup, group) { return __awaiter(_this, void 0, void 0, function () {
299
+ var _this = this;
300
+ return __generator(this, function (_a) {
301
+ switch (_a.label) {
302
+ case 0: return [4 /*yield*/, previousGroup];
303
+ case 1:
304
+ _a.sent();
305
+ return [2 /*return*/, Promise.all(Object.keys(group).map(function (table) { return _this.knexHandle(table).withSchema(_this.config.dbSchema).insert(group[table]); }))];
306
+ }
307
+ });
308
+ }); }, Promise.resolve())];
309
+ });
310
+ });
311
+ };
312
+ DbMigratorAndSeeder.prototype.runSeeds = function (dirname, seedFiles) {
313
+ return __awaiter(this, void 0, void 0, function () {
314
+ var groups;
315
+ return __generator(this, function (_a) {
316
+ switch (_a.label) {
317
+ case 0: return [4 /*yield*/, this.generateSeeds(dirname, seedFiles)];
318
+ case 1:
319
+ groups = _a.sent();
320
+ return [4 /*yield*/, this.removeSeedsFromDb(seedFiles)];
321
+ case 2:
322
+ _a.sent();
323
+ return [4 /*yield*/, this.insertRecords(groups)];
324
+ case 3: return [2 /*return*/, _a.sent()];
325
+ }
326
+ });
327
+ });
328
+ };
329
+ return DbMigratorAndSeeder;
330
+ }());
331
+ exports.DbMigratorAndSeeder = DbMigratorAndSeeder;
package/build/index.d.ts CHANGED
@@ -3,6 +3,7 @@ export { CacheInterface, LoaderInterface, BaseGatewayInterface, ListArgsInterfac
3
3
  export { buildConfig } from './configBulder';
4
4
  export { Database } from './database';
5
5
  export { dbCleanTable, dbListTables, dbClean, dbWipe, dbReset, dbTransformSeedsToObject, dbRunMigrations, } from './dbHelpers';
6
+ export { DbMigratorAndSeeder } from './dbMigratorAndSeeder';
6
7
  export { dbSeed } from './dbSeeder';
7
8
  export { buildKnexConfig } from './knexConfigBuilder';
8
9
  export { createRedisClient } from './redisClient';
@@ -14,4 +15,5 @@ export { createApiContext } from './apiContext';
14
15
  export { BaseController } from './baseController';
15
16
  export { dbFieldAddDefaults } from './dbTableHelpers';
16
17
  export { buildDefaultResolvers } from './resolversHelpers';
18
+ export { createUserToken, verifyUserToken } from './userToken';
17
19
  export { constants };
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.dbRunMigrations = exports.dbTransformSeedsToObject = exports.dbReset = exports.dbWipe = exports.dbClean = exports.dbListTables = exports.dbCleanTable = exports.Database = exports.buildConfig = void 0;
6
+ exports.constants = exports.verifyUserToken = exports.createUserToken = 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;
7
7
  var constants_1 = __importDefault(require("./constants"));
8
8
  exports.constants = constants_1.default;
9
9
  var configBulder_1 = require("./configBulder");
@@ -18,6 +18,8 @@ Object.defineProperty(exports, "dbWipe", { enumerable: true, get: function () {
18
18
  Object.defineProperty(exports, "dbReset", { enumerable: true, get: function () { return dbHelpers_1.dbReset; } });
19
19
  Object.defineProperty(exports, "dbTransformSeedsToObject", { enumerable: true, get: function () { return dbHelpers_1.dbTransformSeedsToObject; } });
20
20
  Object.defineProperty(exports, "dbRunMigrations", { enumerable: true, get: function () { return dbHelpers_1.dbRunMigrations; } });
21
+ var dbMigratorAndSeeder_1 = require("./dbMigratorAndSeeder");
22
+ Object.defineProperty(exports, "DbMigratorAndSeeder", { enumerable: true, get: function () { return dbMigratorAndSeeder_1.DbMigratorAndSeeder; } });
21
23
  var dbSeeder_1 = require("./dbSeeder");
22
24
  Object.defineProperty(exports, "dbSeed", { enumerable: true, get: function () { return dbSeeder_1.dbSeed; } });
23
25
  var knexConfigBuilder_1 = require("./knexConfigBuilder");
@@ -41,3 +43,6 @@ var dbTableHelpers_1 = require("./dbTableHelpers");
41
43
  Object.defineProperty(exports, "dbFieldAddDefaults", { enumerable: true, get: function () { return dbTableHelpers_1.dbFieldAddDefaults; } });
42
44
  var resolversHelpers_1 = require("./resolversHelpers");
43
45
  Object.defineProperty(exports, "buildDefaultResolvers", { enumerable: true, get: function () { return resolversHelpers_1.buildDefaultResolvers; } });
46
+ var userToken_1 = require("./userToken");
47
+ Object.defineProperty(exports, "createUserToken", { enumerable: true, get: function () { return userToken_1.createUserToken; } });
48
+ Object.defineProperty(exports, "verifyUserToken", { enumerable: true, get: function () { return userToken_1.verifyUserToken; } });
@@ -25,32 +25,32 @@ export interface BaseCoreInterface {
25
25
  logger?: Logger;
26
26
  name?: string;
27
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[];
28
+ beforeList?(params: any, gateways?: any, opt?: any): any;
29
+ beforeCreate?(params: any, gateways?: any, opt?: any): any;
30
+ beforeCreateMany?(params: any, gateways?: any, opt?: any): any;
31
+ beforeUpdate?(params: any, gateways?: any, opt?: any): any;
32
+ beforeUpdateMany?(params: any, gateways?: any, opt?: any): any;
33
+ beforeSet?(params: any, gateways?: any, opt?: any): any;
34
+ beforeRemove?(params: any, gateways?: any, opt?: any): any;
35
+ beforeRemoveMany?(params: any, gateways?: any, opt?: any): any;
36
+ afterList?(params: any, gateways?: any, opt?: any): any;
37
+ afterCreate?(params: any, gateways?: any, opt?: any): any;
38
+ afterCreateMany?(params: any, gateways?: any, opt?: any): any;
39
+ afterUpdate?(params: any, gateways?: any, opt?: any): any;
40
+ afterUpdateMany?(params: any, gateways?: any, opt?: any): any;
41
+ afterSet?(params: any, gateways?: any, opt?: any): any;
42
+ afterRemove?(params: any, gateways?: any, opt?: any): any;
43
+ afterRemoveMany?(params: any, gateways?: any, opt?: any): any;
44
+ validateList?(params: any, gateways?: any, opt?: any): Promise<any[]> | any[];
45
+ validateGet?(params: any, gateways?: any, opt?: any): Promise<any[]> | any[];
46
+ validateGetMany?(params: any, gateways?: any, opt?: any): Promise<any[]> | any[];
47
+ validateCreate?(params: any, gateways?: any, opt?: any): Promise<any[]> | any[];
48
+ validateCreateMany?(params: any, gateways?: any, opt?: any): Promise<any[]> | any[];
49
+ validateUpdate?(params: any, gateways?: any, opt?: any): Promise<any[]> | any[];
50
+ validateUpdateMany?(params: any, gateways?: any, opt?: any): Promise<any[]> | any[];
51
+ validateSet?(params: any, gateways?: any, opt?: any): Promise<any[]> | any[];
52
+ validateRemove?(params: any, gateways?: any, opt?: any): Promise<any[]> | any[];
53
+ validateRemoveMany?(params: any, gateways?: any, opt?: any): Promise<any[]> | any[];
54
54
  validators?: BaseCoreValidatorsInterface;
55
55
  authenticate?(params: any): Promise<any[]> | any[];
56
56
  doAuth: boolean;
@@ -1,12 +1,12 @@
1
1
  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[];
2
+ list?(params: any, gateways?: any, opt?: any): Promise<any[]> | any[];
3
+ get?(params: any, gateways?: any, opt?: any): Promise<any[]> | any[];
4
+ getMany?(params: any, gateways?: any, opt?: any): Promise<any[]> | any[];
5
+ create?(params: any, gateways?: any, opt?: any): Promise<any[]> | any[];
6
+ createMany?(params: any, gateways?: any, opt?: any): Promise<any[]> | any[];
7
+ update?(params: any, gateways?: any, opt?: any): Promise<any[]> | any[];
8
+ updateMany?(params: any, gateways?: any, opt?: any): Promise<any[]> | any[];
9
+ set?(params: any, gateways?: any, opt?: any): Promise<any[]> | any[];
10
+ remove?(params: any, gateways?: any, opt?: any): Promise<any[]> | any[];
11
+ removeMany?(params: any, gateways?: any, opt?: any): Promise<any[]> | any[];
12
12
  }
@@ -6,6 +6,7 @@ export interface BaseGatewayInterface {
6
6
  db: Database;
7
7
  table?: string;
8
8
  idField?: string;
9
+ setFields?: string[] | string;
9
10
  selectFields?: any[];
10
11
  defaultSorting?: SortItemInterface[];
11
12
  filter?(query: any, params: any): any;
@@ -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,6 @@
1
+ export interface UserTokenParams {
2
+ accountId: string;
3
+ roleId: string;
4
+ userId: string;
5
+ [tokenProp: string]: string;
6
+ }
@@ -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 });
@@ -13,3 +13,6 @@ 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';
@@ -13,7 +13,7 @@ var __assign = (this && this.__assign) || function () {
13
13
  Object.defineProperty(exports, "__esModule", { value: true });
14
14
  exports.buildDefaultResolvers = void 0;
15
15
  var buildDefaultResolvers = function (args) {
16
- var _a = args || {}, prefix = _a.prefix, core = _a.core, query = _a.query, mutation = _a.mutation, types = _a.types, disableList = _a.disableList, disableGet = _a.disableGet, disableGetMany = _a.disableGetMany, disableCreate = _a.disableCreate, disableCreateMany = _a.disableCreateMany, disableUpdate = _a.disableUpdate, disableUpdateMany = _a.disableUpdateMany, disableRemove = _a.disableRemove, disableRemoveMany = _a.disableRemoveMany;
16
+ var _a = args || {}, prefix = _a.prefix, core = _a.core, query = _a.query, mutation = _a.mutation, types = _a.types, disableList = _a.disableList, disableGet = _a.disableGet, disableGetMany = _a.disableGetMany, disableCreate = _a.disableCreate, disableCreateMany = _a.disableCreateMany, disableUpdate = _a.disableUpdate, disableUpdateMany = _a.disableUpdateMany, disableSet = _a.disableSet, disableRemove = _a.disableRemove, disableRemoveMany = _a.disableRemoveMany;
17
17
  var Query = __assign({}, (query || {}));
18
18
  var Mutation = __assign({}, (mutation || {}));
19
19
  if (disableList !== true) {
@@ -51,6 +51,11 @@ var buildDefaultResolvers = function (args) {
51
51
  return context[core].updateMany(args);
52
52
  };
53
53
  }
54
+ if (disableSet !== true) {
55
+ Mutation[prefix + "Set"] = function (parent, args, context) {
56
+ return context[core].set(args);
57
+ };
58
+ }
54
59
  if (disableRemove !== true) {
55
60
  Mutation[prefix + "Remove"] = function (parent, args, context) {
56
61
  return context[core].remove(args);
@@ -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.10",
3
+ "version": "1.0.15",
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",