@sdflc/backend-helpers 1.0.16 → 1.0.20

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,59 @@ 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 managementApiKey = req.headers['x-management-api-key'];
49
+ var accountId = req.headers['x-account-id'];
50
+ var roleId = req.headers['x-role-id'];
51
+ var userId = req.headers['x-user-id'];
52
+ var userAgent = req.headers['user-agent'];
53
+ var referer = req.headers['referer'];
54
+ var ipAddress = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
55
+ var acceptLanguage = req.headers['accept-language'];
56
+ var languages = utils_1.extractLanguages(acceptLanguage);
57
+ var requestedLang = req.query['lang'];
58
+ var requestId = uuid_1.v4();
59
+ var db = new database_1.Database({
60
+ knexConfig: knexConfig,
61
+ dbSchema: dbSchema,
62
+ });
63
+ return exports.createApiContext({
64
+ cores: cores,
65
+ req: req,
66
+ requestId: requestId,
67
+ extendContext: function (_a) {
68
+ var context = _a.context /*, req */;
69
+ context.db = db;
70
+ },
71
+ getCoreContext: function ( /*args: any*/) {
72
+ // TODO: const { req } = args;
73
+ return {
74
+ db: db,
75
+ context: {
76
+ spaceId: spaceId,
77
+ apiKey: apiKey,
78
+ managementApiKey: managementApiKey,
79
+ userAgent: userAgent,
80
+ referer: referer,
81
+ ipAddress: ipAddress,
82
+ acceptLanguage: acceptLanguage,
83
+ languages: languages,
84
+ requestedLang: requestedLang,
85
+ authorization: authorization,
86
+ accountId: accountId,
87
+ roleId: roleId,
88
+ userId: userId,
89
+ },
90
+ };
91
+ },
92
+ });
93
+ };
94
+ 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, opt) {
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,12 +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(), {
236
- core: this,
237
- setStep: setStep,
238
- sameRequest: sameRequest,
239
- hasTransaction: hasTransaction,
240
- })];
242
+ return [4 /*yield*/, validate(args, actionOpt)];
241
243
  case 6:
242
244
  valideResult = _c.sent();
243
245
  result_1 = valideResult;
@@ -254,7 +256,7 @@ var BaseCore = /** @class */ (function () {
254
256
  // if there was an error then `result` is expected to be an object with the same structure as the checkit library does
255
257
  _c.sent();
256
258
  return [2 /*return*/, result_1.code != null ? result_1 : new api_helpers_1.OpResult({ code: api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED })];
257
- 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 }))];
258
260
  case 9:
259
261
  result = _c.sent();
260
262
  return [4 /*yield*/, this.checkResult({ hasTransaction: hasTransaction, result: result, sameRequest: sameRequest })];
@@ -268,7 +270,9 @@ var BaseCore = /** @class */ (function () {
268
270
  case 12:
269
271
  _c.sent();
270
272
  _c.label = 13;
271
- 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();
272
276
  what = doingWhat;
273
277
  if (doingWhat !== step) {
274
278
  what = {
@@ -276,7 +280,7 @@ var BaseCore = /** @class */ (function () {
276
280
  };
277
281
  }
278
282
  return [2 /*return*/, this.exceptionFailure(ex_1, what)];
279
- case 14: return [2 /*return*/];
283
+ case 15: return [2 /*return*/];
280
284
  }
281
285
  });
282
286
  });
@@ -297,17 +301,17 @@ var BaseCore = /** @class */ (function () {
297
301
  switch (_b.label) {
298
302
  case 0:
299
303
  this.logger.log("Requesting a list for " + this.name + ":", args);
300
- return [4 /*yield*/, this.beforeList(args, this.getGateways(), __assign({ core: this }, opt))];
304
+ return [4 /*yield*/, this.beforeList(args, opt)];
301
305
  case 1:
302
306
  object = _b.sent();
303
307
  return [4 /*yield*/, ((_a = this.gateway) === null || _a === void 0 ? void 0 : _a.list(object))];
304
308
  case 2:
305
309
  items = _b.sent();
306
- return [4 /*yield*/, this.afterList(items, this.getGateways(), __assign({ core: this }, opt))];
310
+ return [4 /*yield*/, this.afterList(items, opt)];
307
311
  case 3:
308
312
  result = _b.sent();
309
313
  // ON NO DATA RETURN EMPTY CODE
310
- return [2 /*return*/, this.success(result)];
314
+ return [2 /*return*/, this.success(result /*, result.length > 0 OP_RESULT_CODES.OK : OP_RESULT_CODES.*/)];
311
315
  }
312
316
  });
313
317
  }); },
@@ -394,20 +398,20 @@ var BaseCore = /** @class */ (function () {
394
398
  case 0:
395
399
  params = (args || {}).params;
396
400
  this.logger.log("Requesting creation of an item for " + this.name + ":", args);
397
- return [4 /*yield*/, this.beforeCreate(params, this.getGateways(), __assign({ core: this }, opt))];
401
+ return [4 /*yield*/, this.beforeCreate(params, opt)];
398
402
  case 1:
399
403
  object = _b.sent();
400
404
  return [4 /*yield*/, ((_a = this.gateway) === null || _a === void 0 ? void 0 : _a.create(object))];
401
405
  case 2:
402
406
  item = _b.sent();
403
- return [4 /*yield*/, this.afterCreate(item, this.getGateways(), __assign({ core: this }, opt))];
407
+ return [4 /*yield*/, this.afterCreate(item, opt)];
404
408
  case 3:
405
409
  result = _b.sent();
406
410
  return [2 /*return*/, this.success(result)];
407
411
  }
408
412
  });
409
413
  }); },
410
- hasTransaction: false,
414
+ hasTransaction: true,
411
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',
412
416
  })];
413
417
  });
@@ -430,20 +434,20 @@ var BaseCore = /** @class */ (function () {
430
434
  case 0:
431
435
  params = (args || {}).params;
432
436
  this.logger.log("Requesting creation of multiple items for " + this.name + ":", args);
433
- return [4 /*yield*/, this.beforeCreateMany(params, this.getGateways(), __assign({ core: this }, opt))];
437
+ return [4 /*yield*/, this.beforeCreateMany(params, opt)];
434
438
  case 1:
435
439
  objects = _b.sent();
436
440
  return [4 /*yield*/, ((_a = this.gateway) === null || _a === void 0 ? void 0 : _a.create(objects))];
437
441
  case 2:
438
442
  items = _b.sent();
439
- return [4 /*yield*/, this.afterCreateMany(items, this.getGateways(), __assign({ core: this }, opt))];
443
+ return [4 /*yield*/, this.afterCreateMany(items, opt)];
440
444
  case 3:
441
445
  result = _b.sent();
442
446
  return [2 /*return*/, this.success(result)];
443
447
  }
444
448
  });
445
449
  }); },
446
- hasTransaction: false,
450
+ hasTransaction: true,
447
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',
448
452
  })];
449
453
  });
@@ -466,20 +470,20 @@ var BaseCore = /** @class */ (function () {
466
470
  case 0:
467
471
  _a = args || {}, where = _a.where, params = _a.params;
468
472
  this.logger.log("Requesting update of an item for " + this.name + ":", args);
469
- return [4 /*yield*/, this.beforeUpdate(params, this.getGateways(), __assign({ core: this }, opt))];
473
+ return [4 /*yield*/, this.beforeUpdate(params, opt)];
470
474
  case 1:
471
475
  object = _c.sent();
472
476
  return [4 /*yield*/, ((_b = this.gateway) === null || _b === void 0 ? void 0 : _b.update(where, object))];
473
477
  case 2:
474
478
  item = _c.sent();
475
- return [4 /*yield*/, this.afterUpdate(item, this.getGateways(), __assign({ core: this }, opt))];
479
+ return [4 /*yield*/, this.afterUpdate(item, opt)];
476
480
  case 3:
477
481
  result = _c.sent();
478
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)];
479
483
  }
480
484
  });
481
485
  }); },
482
- hasTransaction: false,
486
+ hasTransaction: true,
483
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',
484
488
  })];
485
489
  });
@@ -502,20 +506,20 @@ var BaseCore = /** @class */ (function () {
502
506
  case 0:
503
507
  params = (args || {}).params;
504
508
  this.logger.log("Requesting update of an item for " + this.name + ":", args);
505
- return [4 /*yield*/, this.beforeUpdateMany(params, this.getGateways(), __assign({ core: this }, opt))];
509
+ return [4 /*yield*/, this.beforeUpdateMany(params, opt)];
506
510
  case 1:
507
511
  object = _b.sent();
508
512
  return [4 /*yield*/, ((_a = this.gateway) === null || _a === void 0 ? void 0 : _a.updateMany(object))];
509
513
  case 2:
510
514
  items = _b.sent();
511
- return [4 /*yield*/, this.afterUpdateMany(items, this.getGateways(), __assign({ core: this }, opt))];
515
+ return [4 /*yield*/, this.afterUpdateMany(items, opt)];
512
516
  case 3:
513
517
  result = _b.sent();
514
518
  return [2 /*return*/, this.success(result)];
515
519
  }
516
520
  });
517
521
  }); },
518
- hasTransaction: false,
522
+ hasTransaction: true,
519
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',
520
524
  })];
521
525
  });
@@ -538,20 +542,20 @@ var BaseCore = /** @class */ (function () {
538
542
  case 0:
539
543
  params = (args || {}).params;
540
544
  this.logger.log("Requesting setting of item(s) for " + this.name + ":", args);
541
- return [4 /*yield*/, this.beforeSet(params, __assign({ core: this }, opt))];
545
+ return [4 /*yield*/, this.beforeSet(params, opt)];
542
546
  case 1:
543
547
  object = _b.sent();
544
548
  return [4 /*yield*/, ((_a = this.gateway) === null || _a === void 0 ? void 0 : _a.set(object))];
545
549
  case 2:
546
550
  items = _b.sent();
547
- return [4 /*yield*/, this.afterSet(items, __assign({ core: this }, opt))];
551
+ return [4 /*yield*/, this.afterSet(items, opt)];
548
552
  case 3:
549
553
  result = _b.sent();
550
554
  return [2 /*return*/, this.success(result)];
551
555
  }
552
556
  });
553
557
  }); },
554
- hasTransaction: false,
558
+ hasTransaction: true,
555
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',
556
560
  })];
557
561
  });
@@ -574,13 +578,13 @@ var BaseCore = /** @class */ (function () {
574
578
  case 0:
575
579
  where = (args || {}).where;
576
580
  this.logger.log("Requesting removal of an item for " + this.name + ":", args);
577
- return [4 /*yield*/, this.beforeRemove(where, this.getGateways(), __assign({ core: this }, opt))];
581
+ return [4 /*yield*/, this.beforeRemove(where, opt)];
578
582
  case 1:
579
583
  object = _b.sent();
580
584
  return [4 /*yield*/, ((_a = this.gateway) === null || _a === void 0 ? void 0 : _a.remove(object))];
581
585
  case 2:
582
586
  items = _b.sent();
583
- return [4 /*yield*/, this.afterRemove(items, this.getGateways(), __assign({ core: this }, opt))];
587
+ return [4 /*yield*/, this.afterRemove(items, opt)];
584
588
  case 3:
585
589
  result = _b.sent();
586
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)];
@@ -610,13 +614,13 @@ var BaseCore = /** @class */ (function () {
610
614
  case 0:
611
615
  where = (args || {}).where;
612
616
  this.logger.log("Requesting removal of multiple items for " + this.name + ":", args);
613
- return [4 /*yield*/, this.beforeRemoveMany(where, this.getGateways(), __assign({ core: this }, opt))];
617
+ return [4 /*yield*/, this.beforeRemoveMany(where, opt)];
614
618
  case 1:
615
619
  object = _b.sent();
616
620
  return [4 /*yield*/, ((_a = this.gateway) === null || _a === void 0 ? void 0 : _a.remove(object))];
617
621
  case 2:
618
622
  items = _b.sent();
619
- return [4 /*yield*/, this.afterRemoveMany(items, this.getGateways(), __assign({ core: this }, opt))];
623
+ return [4 /*yield*/, this.afterRemoveMany(items, opt)];
620
624
  case 3:
621
625
  result = _b.sent();
622
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,8 +13,9 @@ declare class BaseGateway {
12
13
  constructor(props: BaseGatewayInterface);
13
14
  getDb(): import("./database").Database;
14
15
  getBuilder(): any;
15
- getIdField(): string;
16
- getCore(): import("./baseCore").BaseCore;
16
+ getIdField(): any;
17
+ getCore(): BaseCore;
18
+ setCore(core: BaseCore): void;
17
19
  get(id: any): Promise<any>;
18
20
  getMany(ids: any[]): Promise<any>;
19
21
  list(args?: ListArgsInterface): Promise<any>;
@@ -103,6 +103,9 @@ var BaseGateway = /** @class */ (function () {
103
103
  BaseGateway.prototype.getCore = function () {
104
104
  return this.config.core;
105
105
  };
106
+ BaseGateway.prototype.setCore = function (core) {
107
+ this.config.core = core;
108
+ };
106
109
  BaseGateway.prototype.get = function (id) {
107
110
  return __awaiter(this, void 0, void 0, function () {
108
111
  return __generator(this, function (_a) {
@@ -221,6 +224,7 @@ var BaseGateway = /** @class */ (function () {
221
224
  BaseGateway.prototype.updateMany = function (params) {
222
225
  return __awaiter(this, void 0, void 0, function () {
223
226
  var results, idx, len, item, items;
227
+ var _this = this;
224
228
  return __generator(this, function (_a) {
225
229
  switch (_a.label) {
226
230
  case 0:
@@ -241,7 +245,11 @@ var BaseGateway = /** @class */ (function () {
241
245
  case 3:
242
246
  ++idx;
243
247
  return [3 /*break*/, 1];
244
- 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];
245
253
  }
246
254
  });
247
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, returnFields = args.returnFields;
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: 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',
@@ -12,13 +13,19 @@ var constants = {
12
13
  UPDATED_AT: 'updated_at',
13
14
  REMOVED_AT: 'removed_at',
14
15
  REMOVED_AT_STR: 'removed_at_str',
16
+ LANG: 'LANG',
17
+ ACCOUNT_ID: 'account_id',
18
+ ROLE_ID: 'role_id',
19
+ USER_ID: 'user_id',
15
20
  },
16
21
  STATUSES: {
17
22
  TEST: 50,
18
23
  ACTIVE: 100,
19
24
  DRAFT: 200,
20
- DISABLED: 300,
21
- REMOVED: 1000,
25
+ PENDING: 300,
26
+ BLOCKED: 1000,
27
+ DISABLED: 5000,
28
+ REMOVED: 10000,
22
29
  },
23
30
  ACCESS_RIGHTS: {
24
31
  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, UserTokenParams, CreateUserTokenArgs, VerifyUserTokenArgs, BaseCoreActionsInterface, } 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,9 +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
18
  export { createUserToken, verifyUserToken } from './userToken';
19
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.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;
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,6 +37,7 @@ 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");
@@ -46,3 +47,5 @@ Object.defineProperty(exports, "buildDefaultResolvers", { enumerable: true, get:
46
47
  var userToken_1 = require("./userToken");
47
48
  Object.defineProperty(exports, "createUserToken", { enumerable: true, get: function () { return userToken_1.createUserToken; } });
48
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, 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
- 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, 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[];
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,4 +1,5 @@
1
1
  export interface UserTokenParams {
2
+ spaceId: string;
2
3
  accountId: string;
3
4
  roleId: string;
4
5
  userId: string;
@@ -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';
@@ -16,3 +16,5 @@ export { BaseCoreValidatorsInterface } from './BaseCoreValidatorsInterface';
16
16
  export { UserTokenParams } from './UserTokenParams';
17
17
  export { CreateUserTokenArgs } from './CreateUserTokenArgs';
18
18
  export { VerifyUserTokenArgs } from './VerifyUserTokenArgs';
19
+ export { BaseCoreActionsInterface } from './BaseCoreActionsInterface';
20
+ export { BaseCoreDoingWhatInterface } from './BaseCoreDoingWhatInterface';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sdflc/backend-helpers",
3
- "version": "1.0.16",
3
+ "version": "1.0.20",
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",