@sdflc/backend-helpers 1.0.6 → 1.0.10

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.
@@ -1,19 +1,33 @@
1
1
  "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
2
13
  Object.defineProperty(exports, "__esModule", { value: true });
3
14
  exports.createApiContext = void 0;
4
15
  var lodash_1 = require("lodash");
16
+ var uuid_1 = require("uuid");
5
17
  /**
6
18
  * Creates a GraphQL context object with all available cores.
7
19
  * @returns {object} A context object with all available cores
8
20
  */
9
21
  var createApiContext = function (args) {
10
- var _a = args || {}, cores = _a.cores, req = _a.req, getCoreContext = _a.getCoreContext, extendContext = _a.extendContext;
22
+ var _a = args || {}, cores = _a.cores, req = _a.req, getCoreContext = _a.getCoreContext, extendContext = _a.extendContext, inRequestId = _a.requestId;
11
23
  var keys = Object.keys(cores || {});
24
+ var requestId = inRequestId || uuid_1.v4();
12
25
  var coreContext = typeof getCoreContext === 'function' ? getCoreContext({ req: req }) : {};
13
26
  var context = keys.reduce(function (acc, key) {
14
- acc[lodash_1.camelCase(key)] = new cores[key](coreContext);
27
+ acc[lodash_1.camelCase(key)] = new cores[key](__assign(__assign({}, coreContext), { requestId: requestId }));
15
28
  return acc;
16
29
  }, {});
30
+ context.requestId = requestId;
17
31
  if (typeof extendContext === 'function') {
18
32
  extendContext({ context: context, req: req });
19
33
  }
@@ -16,6 +16,7 @@ declare class BaseCore {
16
16
  protected beforeCreateMany: any;
17
17
  protected beforeUpdate: any;
18
18
  protected beforeUpdateMany: any;
19
+ protected beforeSet: any;
19
20
  protected beforeRemove: any;
20
21
  protected beforeRemoveMany: any;
21
22
  protected afterList: any;
@@ -23,13 +24,16 @@ declare class BaseCore {
23
24
  protected afterCreateMany: any;
24
25
  protected afterUpdate: any;
25
26
  protected afterUpdateMany: any;
27
+ protected afterSet: any;
26
28
  protected afterRemove: any;
27
29
  protected afterRemoveMany: any;
30
+ protected requestId: string;
28
31
  protected validators: BaseCoreValidatorsInterface;
29
32
  protected authenticate: any;
30
33
  protected doAuth: boolean;
31
34
  constructor(props: BaseCoreInterface);
32
35
  getDb(): Database;
36
+ getRequestId(): string;
33
37
  getContext(key?: string): any;
34
38
  getGateways(): any;
35
39
  success(data: any, code?: number): any;
@@ -45,6 +49,7 @@ declare class BaseCore {
45
49
  createMany(args: any): Promise<any>;
46
50
  update(args: any): Promise<any>;
47
51
  updateMany(args: any): Promise<any>;
52
+ set(args: any): Promise<any>;
48
53
  remove(args: any): Promise<any>;
49
54
  removeMany(args: any): Promise<any>;
50
55
  }
package/build/baseCore.js CHANGED
@@ -70,6 +70,7 @@ var defaultValidators = {
70
70
  createMany: defaultValidate,
71
71
  update: defaultValidate,
72
72
  updateMany: defaultValidate,
73
+ set: defaultValidate,
73
74
  remove: defaultValidate,
74
75
  removeMany: defaultValidate,
75
76
  };
@@ -93,6 +94,7 @@ var BaseCore = /** @class */ (function () {
93
94
  this.beforeUpdate = typeof props.beforeUpdate === 'function' ? props.beforeUpdate : defaultAfterAndBefore;
94
95
  this.beforeUpdateMany =
95
96
  typeof props.beforeUpdateMany === 'function' ? props.beforeUpdateMany : defaultAfterAndBefore;
97
+ this.beforeSet = typeof props.beforeSet === 'function' ? props.beforeSet : defaultAfterAndBefore;
96
98
  this.beforeRemove = typeof props.beforeRemove === 'function' ? props.beforeRemove : defaultAfterAndBefore;
97
99
  this.beforeRemoveMany =
98
100
  typeof props.beforeRemoveMany === 'function' ? props.beforeRemoveMany : defaultAfterAndBefore;
@@ -101,15 +103,20 @@ var BaseCore = /** @class */ (function () {
101
103
  this.afterCreateMany = typeof props.afterCreateMany === 'function' ? props.afterCreateMany : defaultAfterAndBefore;
102
104
  this.afterUpdate = typeof props.afterUpdate === 'function' ? props.afterUpdate : defaultAfterAndBefore;
103
105
  this.afterUpdateMany = typeof props.afterUpdateMany === 'function' ? props.afterUpdateMany : defaultAfterAndBefore;
106
+ this.afterSet = typeof props.afterSet === 'function' ? props.afterSet : defaultAfterAndBefore;
104
107
  this.afterRemove = typeof props.afterRemove === 'function' ? props.afterRemove : defaultAfterAndBefore;
105
108
  this.afterRemoveMany = typeof props.afterRemoveMany === 'function' ? props.afterRemoveMany : defaultAfterAndBefore;
106
109
  this.validators = utils_2.setFunctions((props === null || props === void 0 ? void 0 : props.validators) || {}, this.validators);
107
110
  this.authenticate = typeof props.authenticate === 'function' ? props.authenticate : defaultAuth;
108
111
  this.doAuth = props.doAuth === true;
112
+ this.requestId = props.requestId || '';
109
113
  }
110
114
  BaseCore.prototype.getDb = function () {
111
115
  return this.db;
112
116
  };
117
+ BaseCore.prototype.getRequestId = function () {
118
+ return this.requestId;
119
+ };
113
120
  BaseCore.prototype.getContext = function (key) {
114
121
  return key ? this.context[key] : this.context;
115
122
  };
@@ -169,11 +176,14 @@ var BaseCore = /** @class */ (function () {
169
176
  };
170
177
  BaseCore.prototype.checkResult = function (args) {
171
178
  return __awaiter(this, void 0, void 0, function () {
172
- var hasTransaction, result;
179
+ var hasTransaction, result, sameRequest;
173
180
  return __generator(this, function (_a) {
174
181
  switch (_a.label) {
175
182
  case 0:
176
- hasTransaction = args.hasTransaction, result = args.result;
183
+ hasTransaction = args.hasTransaction, result = args.result, sameRequest = args.sameRequest;
184
+ if (sameRequest) {
185
+ return [2 /*return*/];
186
+ }
177
187
  if (!(hasTransaction && result)) return [3 /*break*/, 4];
178
188
  if (!(result.code >= api_helpers_1.OP_RESULT_CODES.OK)) return [3 /*break*/, 2];
179
189
  return [4 /*yield*/, this.db.commitTransaction()];
@@ -191,11 +201,12 @@ var BaseCore = /** @class */ (function () {
191
201
  };
192
202
  BaseCore.prototype.runAction = function (opt) {
193
203
  return __awaiter(this, void 0, void 0, function () {
194
- var _a, args, validate, doAuth, action, hasTransaction, doingWhat, step, setStep, _b, authResult, errMsg, validatedItems, valideResult, result_1, result, ex_1, what;
204
+ var _a, args, validate, doAuth, action, hasTransaction, doingWhat, sameRequest, step, setStep, _b, authResult, errMsg, validatedItems, valideResult, result_1, result, ex_1, what;
195
205
  return __generator(this, function (_c) {
196
206
  switch (_c.label) {
197
207
  case 0:
198
208
  _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;
199
210
  step = doingWhat || '';
200
211
  setStep = function (stepName) {
201
212
  step = stepName;
@@ -203,6 +214,7 @@ var BaseCore = /** @class */ (function () {
203
214
  _c.label = 1;
204
215
  case 1:
205
216
  _c.trys.push([1, 11, , 14]);
217
+ if (!!sameRequest) return [3 /*break*/, 5];
206
218
  if (!hasTransaction) return [3 /*break*/, 3];
207
219
  return [4 /*yield*/, this.db.startTransaction()];
208
220
  case 2:
@@ -232,21 +244,21 @@ var BaseCore = /** @class */ (function () {
232
244
  result_1 = result_1 != null ? result_1 : true;
233
245
  if (!(result_1 !== true)) return [3 /*break*/, 8];
234
246
  // if there was an error then `result` is expected to be an object with the same structure as the checkit library does
235
- return [4 /*yield*/, this.checkResult({ hasTransaction: hasTransaction, result: result_1 })];
247
+ return [4 /*yield*/, this.checkResult({ hasTransaction: hasTransaction, result: result_1, sameRequest: sameRequest })];
236
248
  case 7:
237
249
  // if there was an error then `result` is expected to be an object with the same structure as the checkit library does
238
250
  _c.sent();
239
251
  return [2 /*return*/, result_1.code != null ? result_1 : new api_helpers_1.OpResult({ code: api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED })];
240
- case 8: return [4 /*yield*/, action(args, { setStep: setStep, validatedItems: validatedItems })];
252
+ case 8: return [4 /*yield*/, action(args, { setStep: setStep, validatedItems: validatedItems, sameRequest: sameRequest })];
241
253
  case 9:
242
254
  result = _c.sent();
243
- return [4 /*yield*/, this.checkResult({ hasTransaction: hasTransaction, result: result })];
255
+ return [4 /*yield*/, this.checkResult({ hasTransaction: hasTransaction, result: result, sameRequest: sameRequest })];
244
256
  case 10:
245
257
  _c.sent();
246
258
  return [2 /*return*/, result];
247
259
  case 11:
248
260
  ex_1 = _c.sent();
249
- if (!hasTransaction) return [3 /*break*/, 13];
261
+ if (!(!sameRequest && hasTransaction)) return [3 /*break*/, 13];
250
262
  return [4 /*yield*/, this.db.rollbackTransaction()];
251
263
  case 12:
252
264
  _c.sent();
@@ -275,20 +287,20 @@ var BaseCore = /** @class */ (function () {
275
287
  accessRights: [ACCESS_RIGHTS.LIST],
276
288
  action: function (args) { return __awaiter(_this, void 0, void 0, function () {
277
289
  var object, items, result;
278
- var _a, _b;
279
- return __generator(this, function (_c) {
280
- switch (_c.label) {
290
+ var _a;
291
+ return __generator(this, function (_b) {
292
+ switch (_b.label) {
281
293
  case 0:
282
294
  this.logger.log("Requesting a list for " + this.name + ":", args);
283
295
  return [4 /*yield*/, this.beforeList(args, this.getGateways())];
284
296
  case 1:
285
- object = _c.sent();
297
+ object = _b.sent();
286
298
  return [4 /*yield*/, ((_a = this.gateway) === null || _a === void 0 ? void 0 : _a.list(object))];
287
299
  case 2:
288
- items = (_b = (_c.sent())) !== null && _b !== void 0 ? _b : [];
300
+ items = _b.sent();
289
301
  return [4 /*yield*/, this.afterList(items, this.getGateways())];
290
302
  case 3:
291
- result = _c.sent();
303
+ result = _b.sent();
292
304
  // ON NO DATA RETURN EMPTY CODE
293
305
  return [2 /*return*/, this.success(result)];
294
306
  }
@@ -504,6 +516,42 @@ var BaseCore = /** @class */ (function () {
504
516
  });
505
517
  });
506
518
  };
519
+ BaseCore.prototype.set = function (args) {
520
+ var _a, _b, _c;
521
+ return __awaiter(this, void 0, void 0, function () {
522
+ var _this = this;
523
+ return __generator(this, function (_d) {
524
+ return [2 /*return*/, this.runAction({
525
+ args: args,
526
+ validate: this.validators.set,
527
+ accessRights: [ACCESS_RIGHTS.UPDATE, ACCESS_RIGHTS.UPDATE],
528
+ action: function (args) { return __awaiter(_this, void 0, void 0, function () {
529
+ var params, object, items, result;
530
+ var _a;
531
+ return __generator(this, function (_b) {
532
+ switch (_b.label) {
533
+ case 0:
534
+ params = (args || {}).params;
535
+ this.logger.log("Requesting setting of item(s) for " + this.name + ":", args);
536
+ return [4 /*yield*/, this.beforeSet(params, this.getGateways())];
537
+ case 1:
538
+ object = _b.sent();
539
+ return [4 /*yield*/, ((_a = this.gateway) === null || _a === void 0 ? void 0 : _a.set(object))];
540
+ case 2:
541
+ items = _b.sent();
542
+ return [4 /*yield*/, this.afterSet(items, this.getGateways())];
543
+ case 3:
544
+ result = _b.sent();
545
+ return [2 /*return*/, this.success(result)];
546
+ }
547
+ });
548
+ }); },
549
+ hasTransaction: false,
550
+ doingWhat: (_c = (_b = (_a = this.doingWhat) === null || _a === void 0 ? void 0 : _a.updateMany) !== null && _b !== void 0 ? _b : this.name) !== null && _c !== void 0 ? _c : 'updating multiple items',
551
+ })];
552
+ });
553
+ });
554
+ };
507
555
  BaseCore.prototype.remove = function (args) {
508
556
  var _a, _b, _c;
509
557
  return __awaiter(this, void 0, void 0, function () {
@@ -19,6 +19,14 @@ 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
+ /**
23
+ * Inserts or updates data in the database.
24
+ * If the element of given array has not empty id field then the record is updated
25
+ * oterwise inserted
26
+ * @param params Array of objects to update or create
27
+ * @returns Array of updated or inserted objects
28
+ */
29
+ set(params: any): Promise<any[]>;
22
30
  remove(where: any, hardRemove?: boolean): Promise<any>;
23
31
  }
24
32
  export { BaseGateway };
@@ -128,35 +128,37 @@ var BaseGateway = /** @class */ (function () {
128
128
  fieldsToUse = this.config.noCache === true && Array.isArray(this.config.selectFields)
129
129
  ? this.config.selectFields
130
130
  : this.getIdField();
131
- query = query.select(fieldsToUse);
132
- if (typeof this.config.filter === 'function') {
133
- query = this.config.filter(query, filter);
134
- }
131
+ query.select(fieldsToUse);
132
+ if (!(typeof this.config.filter === 'function')) return [3 /*break*/, 2];
133
+ return [4 /*yield*/, this.config.filter(query, filter)];
134
+ case 1:
135
+ _d.sent();
136
+ _d.label = 2;
137
+ case 2:
135
138
  if (limit && !isNaN(limit) && limit > 0) {
136
- query = query.offset(offset).limit(limit);
139
+ query.offset(offset).limit(limit);
137
140
  }
138
141
  if (sortBy) {
139
- query = query.orderBy(sortBy);
142
+ query.orderBy(sortBy);
140
143
  }
141
144
  return [4 /*yield*/, query];
142
- case 1:
145
+ case 3:
143
146
  items = _d.sent();
144
- if (!(this.config.noCache === true)) return [3 /*break*/, 2];
147
+ if (!(this.config.noCache === true)) return [3 /*break*/, 4];
145
148
  _c = items;
146
- return [3 /*break*/, 4];
147
- case 2: return [4 /*yield*/, this.getMany(items.map(function (row) { return row.id; }))];
148
- case 3:
149
+ return [3 /*break*/, 6];
150
+ case 4: return [4 /*yield*/, this.getMany(items.map(function (row) { return row.id; }))];
151
+ case 5:
149
152
  _c = _d.sent();
150
- _d.label = 4;
151
- case 4: return [2 /*return*/, _c];
153
+ _d.label = 6;
154
+ case 6: return [2 /*return*/, _c];
152
155
  }
153
156
  });
154
157
  });
155
158
  };
156
159
  BaseGateway.prototype.create = function (args) {
157
160
  return __awaiter(this, void 0, void 0, function () {
158
- var objects, items;
159
- var _this = this;
161
+ var objects, idx, len, arg, id, items;
160
162
  return __generator(this, function (_a) {
161
163
  switch (_a.label) {
162
164
  case 0:
@@ -167,12 +169,21 @@ var BaseGateway = /** @class */ (function () {
167
169
  if (args.length === 0) {
168
170
  return [2 /*return*/, []];
169
171
  }
170
- args.forEach(function (arg) {
171
- var id = _this.idGenerator(arg);
172
- objects.push(_this.insertFormatter(__assign({ id: id }, arg)));
173
- });
174
- return [4 /*yield*/, this.getBuilder().insert(objects).returning(this.returnFields)];
172
+ idx = 0, len = args.length;
173
+ _a.label = 1;
175
174
  case 1:
175
+ if (!(idx < len)) return [3 /*break*/, 4];
176
+ arg = args[idx];
177
+ return [4 /*yield*/, this.idGenerator(arg)];
178
+ case 2:
179
+ id = _a.sent();
180
+ objects.push(this.insertFormatter(__assign({ id: id }, arg)));
181
+ _a.label = 3;
182
+ case 3:
183
+ ++idx;
184
+ return [3 /*break*/, 1];
185
+ case 4: return [4 /*yield*/, this.getBuilder().insert(objects).returning(this.returnFields)];
186
+ case 5:
176
187
  items = _a.sent();
177
188
  return [2 /*return*/, items];
178
189
  }
@@ -181,15 +192,19 @@ var BaseGateway = /** @class */ (function () {
181
192
  };
182
193
  BaseGateway.prototype.update = function (where, params) {
183
194
  return __awaiter(this, void 0, void 0, function () {
184
- var query, items;
195
+ var object, query, items;
185
196
  var _this = this;
186
197
  return __generator(this, function (_a) {
187
198
  switch (_a.label) {
188
- case 0:
189
- query = this.getBuilder().update(this.updateFormatter(params)).returning(this.returnFields);
190
- query = this.updateFilter(query, where);
191
- return [4 /*yield*/, query];
199
+ case 0: return [4 /*yield*/, this.updateFormatter(params)];
192
200
  case 1:
201
+ object = _a.sent();
202
+ query = this.getBuilder().update(object).returning(this.returnFields);
203
+ return [4 /*yield*/, this.updateFilter(query, where)];
204
+ case 2:
205
+ _a.sent();
206
+ return [4 /*yield*/, query];
207
+ case 3:
193
208
  items = _a.sent();
194
209
  if (items.length > 0 && this.config.noCache !== true) {
195
210
  items.forEach(function (item) { return _this.loader.clear(item[_this.getIdField()]); });
@@ -201,7 +216,7 @@ var BaseGateway = /** @class */ (function () {
201
216
  };
202
217
  BaseGateway.prototype.updateMany = function (params) {
203
218
  return __awaiter(this, void 0, void 0, function () {
204
- var results, idx, len, items;
219
+ var results, idx, len, item, items;
205
220
  return __generator(this, function (_a) {
206
221
  switch (_a.label) {
207
222
  case 0:
@@ -213,7 +228,8 @@ var BaseGateway = /** @class */ (function () {
213
228
  _a.label = 1;
214
229
  case 1:
215
230
  if (!(idx < len)) return [3 /*break*/, 4];
216
- return [4 /*yield*/, this.update(params.where, params.params)];
231
+ item = params[idx];
232
+ return [4 /*yield*/, this.update(item.where, item.params)];
217
233
  case 2:
218
234
  items = _a.sent();
219
235
  results.push(items);
@@ -226,6 +242,51 @@ var BaseGateway = /** @class */ (function () {
226
242
  });
227
243
  });
228
244
  };
245
+ /**
246
+ * Inserts or updates data in the database.
247
+ * If the element of given array has not empty id field then the record is updated
248
+ * oterwise inserted
249
+ * @param params Array of objects to update or create
250
+ * @returns Array of updated or inserted objects
251
+ */
252
+ BaseGateway.prototype.set = function (params) {
253
+ 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) {
258
+ case 0:
259
+ if (!Array.isArray(params)) {
260
+ params = [params];
261
+ }
262
+ results = [];
263
+ idField = this.getIdField();
264
+ idx = 0, len = params.length;
265
+ _b.label = 1;
266
+ 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();
280
+ 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];
286
+ }
287
+ });
288
+ });
289
+ };
229
290
  BaseGateway.prototype.remove = function (where, hardRemove) {
230
291
  if (hardRemove === void 0) { hardRemove = false; }
231
292
  return __awaiter(this, void 0, void 0, function () {
@@ -236,14 +297,16 @@ var BaseGateway = /** @class */ (function () {
236
297
  case 0:
237
298
  query = this.getBuilder();
238
299
  if (hardRemove) {
239
- query = query.delete(this.returnFields);
300
+ query.delete(this.returnFields);
240
301
  }
241
302
  else {
242
- query = query.update(this.removeFormatter()).returning(this.returnFields);
303
+ query.update(this.removeFormatter()).returning(this.returnFields);
243
304
  }
244
- query = this.removeFilter(query, where);
245
- return [4 /*yield*/, query];
305
+ return [4 /*yield*/, this.removeFilter(query, where)];
246
306
  case 1:
307
+ _a.sent();
308
+ return [4 /*yield*/, query];
309
+ case 2:
247
310
  items = _a.sent();
248
311
  if (items.length > 0 && this.config.noCache !== true) {
249
312
  items.forEach(function (item) { return _this.loader.clear(item[_this.getIdField()]); });
@@ -96,7 +96,7 @@ var DataCache = /** @class */ (function () {
96
96
  case 1:
97
97
  dbItems = _a.sent();
98
98
  if (readAll) {
99
- resultItems.push(dbItems);
99
+ resultItems.push.apply(resultItems, dbItems);
100
100
  }
101
101
  else {
102
102
  resultItems.push.apply(resultItems, ids.map(function (id) { return dbItems[_this.buildKey(id)] || null; }));
@@ -4,6 +4,7 @@ declare class Database {
4
4
  private knexHandle;
5
5
  private dbSchema;
6
6
  constructor(props: DatabaseOptions);
7
+ destroy(): void;
7
8
  isDbError(ex: any): any[];
8
9
  createTransaction(trx: any): Promise<unknown>;
9
10
  getSchema(): string;
package/build/database.js CHANGED
@@ -55,6 +55,11 @@ var Database = /** @class */ (function () {
55
55
  this.dbSchema = props.dbSchema || '';
56
56
  this.trx = props.trx;
57
57
  }
58
+ Database.prototype.destroy = function () {
59
+ if (this.knexHandle) {
60
+ this.knexHandle.destroy();
61
+ }
62
+ };
58
63
  Database.prototype.isDbError = function (ex) {
59
64
  var code = (ex || {}).code;
60
65
  switch (code) {
@@ -166,16 +171,18 @@ var Database = /** @class */ (function () {
166
171
  _a = args || {}, where = _a.where, whereIn = _a.whereIn, extendQuery = _a.extendQuery, table = _a.table, selectFields = _a.selectFields, mapBy = _a.mapBy, calculated = _a.calculated, buildKey = _a.buildKey;
167
172
  query = this.getBuilder(table).select(Array.isArray(selectFields) && selectFields.length > 0 ? selectFields : '*');
168
173
  if (where) {
169
- query = query.where(where);
174
+ query.where(where);
170
175
  }
171
176
  if (whereIn) {
172
- query = query.whereIn(whereIn.field, whereIn.values);
177
+ query.whereIn(whereIn.field, whereIn.values);
173
178
  }
174
- if (typeof extendQuery === 'function') {
175
- query = extendQuery(query);
176
- }
177
- return [4 /*yield*/, query];
179
+ if (!(typeof extendQuery === 'function')) return [3 /*break*/, 2];
180
+ return [4 /*yield*/, extendQuery(query)];
178
181
  case 1:
182
+ _b.sent();
183
+ _b.label = 2;
184
+ case 2: return [4 /*yield*/, query];
185
+ case 3:
179
186
  dbResults = _b.sent();
180
187
  if (mapBy) {
181
188
  fnBuildKey_1 = typeof buildKey === 'function' ? buildKey : utils_1.buildKey;
@@ -1,5 +1,7 @@
1
1
  /**
2
- * Removes all the records from provided table
2
+ * Removes all the records from provided table.
3
+ * If appSettings has cleanTable object with table names then
4
+ * it is used to add extra filters to clear the table to avoid for example users data
3
5
  * @param table Name of table from which to remove all the records
4
6
  * @param knexHandle Knex handle object with configured connection to DB
5
7
  * @param appSettings settings with db related information
@@ -42,21 +42,40 @@ 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
43
  var lodash_1 = require("lodash");
44
44
  var bluebird_1 = __importDefault(require("bluebird"));
45
+ var SQLS = {
46
+ pg: {
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 "; },
48
+ listTables: function () { return "\n SELECT TABLE_NAME as table_name\n FROM INFORMATION_SCHEMA.TABLES\n "; },
49
+ 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 "; },
50
+ dropTables: function () { return "\n SELECT 'DROP TABLE IF EXISTS ' || TABLE_NAME || ';' as cmd\n FROM INFORMATION_SCHEMA.TABLES';\n "; },
51
+ },
52
+ };
45
53
  /**
46
- * Removes all the records from provided table
54
+ * Removes all the records from provided table.
55
+ * If appSettings has cleanTable object with table names then
56
+ * it is used to add extra filters to clear the table to avoid for example users data
47
57
  * @param table Name of table from which to remove all the records
48
58
  * @param knexHandle Knex handle object with configured connection to DB
49
59
  * @param appSettings settings with db related information
50
60
  */
51
61
  var dbCleanTable = function (table, knexHandle, appSettings) { return __awaiter(void 0, void 0, void 0, function () {
52
- var tableName;
53
- return __generator(this, function (_a) {
54
- switch (_a.label) {
62
+ var query, cleanTable;
63
+ var _a;
64
+ return __generator(this, function (_b) {
65
+ switch (_b.label) {
55
66
  case 0:
56
- tableName = appSettings.dbSchema ? appSettings.dbSchema + "." + table : table;
57
- return [4 /*yield*/, knexHandle.raw("DELETE FROM " + tableName)];
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) {
72
+ query.where(whereItem.fieldName, whereItem.operand, whereItem.value);
73
+ });
74
+ }
75
+ }
76
+ return [4 /*yield*/, query];
58
77
  case 1:
59
- _a.sent();
78
+ _b.sent();
60
79
  return [2 /*return*/];
61
80
  }
62
81
  });
@@ -74,9 +93,9 @@ var dbListTables = function (knexHandle, appSettings) { return __awaiter(void 0,
74
93
  switch (_a.label) {
75
94
  case 0:
76
95
  skipTables = (appSettings || {}).skipTables || [];
77
- query = "\n SELECT TABLE_NAME as table_name\n FROM INFORMATION_SCHEMA.TABLES\n WHERE TABLE_SCHEMA = '" + appSettings.dbSchema + "';";
96
+ query = SQLS[appSettings.dbType].listTablesSchema(appSettings);
78
97
  if (!appSettings.dbSchema) {
79
- query = "\n SELECT TABLE_NAME as table_name\n FROM INFORMATION_SCHEMA.TABLES";
98
+ query = SQLS[appSettings.dbType].listTables(appSettings);
80
99
  }
81
100
  return [4 /*yield*/, knexHandle.raw(query)];
82
101
  case 1:
@@ -124,12 +143,12 @@ exports.dbClean = dbClean;
124
143
  * TODO: Remove all constraints and then drop tables.
125
144
  */
126
145
  var dbWipe = function (knexHandle, appSettings) {
127
- var qyery = "\n SELECT 'DROP TABLE IF EXISTS " + appSettings.dbSchema + ".' || TABLE_NAME || ';' as cmd\n FROM INFORMATION_SCHEMA.TABLES\n WHERE TABLE_SCHEMA = '" + appSettings.dbSchema + "';\n ";
146
+ var query = SQLS[appSettings.dbType].dropTablesSchema(appSettings);
128
147
  if (!appSettings.dbSchema) {
129
- qyery = "\n SELECT 'DROP TABLE IF EXISTS ' || TABLE_NAME || ';' as cmd\n FROM INFORMATION_SCHEMA.TABLES';\n ";
148
+ query = SQLS[appSettings.dbType].dropTables(appSettings);
130
149
  }
131
150
  return knexHandle
132
- .raw(qyery)
151
+ .raw(query)
133
152
  .then(function (result) { return result.rows.map(function (r) { return r.cmd; }); })
134
153
  .then(function (commands) { return bluebird_1.default.each(commands, function (cmd) { return knexHandle.raw(cmd); }); });
135
154
  };
@@ -1,6 +1,7 @@
1
1
  export interface ApiContextInterface {
2
2
  cores: any;
3
3
  req: any;
4
+ requestId: any;
4
5
  getCoreContext?(args: any): any;
5
6
  extendContext?(args: any): any;
6
7
  }
@@ -10,6 +10,7 @@ export interface DoingWhatInterface {
10
10
  createMany: string;
11
11
  update: string;
12
12
  updateMany: string;
13
+ set: string;
13
14
  remove: string;
14
15
  removeMany: string;
15
16
  [key: string]: string;
@@ -29,6 +30,7 @@ export interface BaseCoreInterface {
29
30
  beforeCreateMany?(params: any, gateways?: any): any;
30
31
  beforeUpdate?(params: any, gateways?: any): any;
31
32
  beforeUpdateMany?(params: any, gateways?: any): any;
33
+ beforeSet?(params: any, gateways?: any): any;
32
34
  beforeRemove?(params: any, gateways?: any): any;
33
35
  beforeRemoveMany?(params: any, gateways?: any): any;
34
36
  afterList?(params: any, gateways?: any): any;
@@ -36,6 +38,7 @@ export interface BaseCoreInterface {
36
38
  afterCreateMany?(params: any, gateways?: any): any;
37
39
  afterUpdate?(params: any, gateways?: any): any;
38
40
  afterUpdateMany?(params: any, gateways?: any): any;
41
+ afterSet?(params: any, gateways?: any): any;
39
42
  afterRemove?(params: any, gateways?: any): any;
40
43
  afterRemoveMany?(params: any, gateways?: any): any;
41
44
  validateList?(params: any, gateways?: any): Promise<any[]> | any[];
@@ -45,9 +48,11 @@ export interface BaseCoreInterface {
45
48
  validateCreateMany?(params: any, gateways?: any): Promise<any[]> | any[];
46
49
  validateUpdate?(params: any, gateways?: any): Promise<any[]> | any[];
47
50
  validateUpdateMany?(params: any, gateways?: any): Promise<any[]> | any[];
51
+ validateSet?(params: any, gateways?: any): Promise<any[]> | any[];
48
52
  validateRemove?(params: any, gateways?: any): Promise<any[]> | any[];
49
53
  validateRemoveMany?(params: any, gateways?: any): Promise<any[]> | any[];
50
54
  validators?: BaseCoreValidatorsInterface;
51
55
  authenticate?(params: any): Promise<any[]> | any[];
52
56
  doAuth: boolean;
57
+ requestId: string;
53
58
  }
@@ -6,6 +6,7 @@ export interface BaseCoreValidatorsInterface {
6
6
  createMany?(params: any, gateways?: any): Promise<any[]> | any[];
7
7
  update?(params: any, gateways?: any): Promise<any[]> | any[];
8
8
  updateMany?(params: any, gateways?: any): Promise<any[]> | any[];
9
+ set?(params: any, gateways?: any): Promise<any[]> | any[];
9
10
  remove?(params: any, gateways?: any): Promise<any[]> | any[];
10
11
  removeMany?(params: any, gateways?: any): Promise<any[]> | any[];
11
12
  }
@@ -11,6 +11,7 @@ export interface BuildDefaultResolvers {
11
11
  disableCreateMany?: boolean;
12
12
  disableUpdate?: boolean;
13
13
  disableUpdateMany?: boolean;
14
+ disableSet?: boolean;
14
15
  disableRemove?: boolean;
15
16
  disableRemoveMany?: boolean;
16
17
  }
@@ -3,4 +3,5 @@ export interface PaginationInterface {
3
3
  page: number;
4
4
  pageSize?: number;
5
5
  sortBy: SortItemInterface[];
6
+ cursor: string;
6
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sdflc/backend-helpers",
3
- "version": "1.0.6",
3
+ "version": "1.0.10",
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",
@@ -30,6 +30,7 @@
30
30
  "@types/lodash": "^4.14.165",
31
31
  "@types/node": "^14.14.10",
32
32
  "@types/redis": "^2.8.29",
33
+ "@types/uuid": "^8.3.1",
33
34
  "@typescript-eslint/eslint-plugin": "^4.9.0",
34
35
  "@typescript-eslint/parser": "^4.11.0",
35
36
  "eslint": "^7.14.0",
@@ -56,6 +57,7 @@
56
57
  "lodash": "^4.17.20",
57
58
  "pg": "^8.6.0",
58
59
  "redis": "^3.1.2",
59
- "redis-dataloader": "^1.0.2"
60
+ "redis-dataloader": "^1.0.2",
61
+ "uuid": "^8.3.2"
60
62
  }
61
63
  }