@intuitionrobotics/db-api-generator 0.41.69 → 0.41.72

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.
@@ -17,30 +17,6 @@
17
17
  * See the License for the specific language governing permissions and
18
18
  * limitations under the License.
19
19
  */
20
- var __extends = (this && this.__extends) || (function () {
21
- var extendStatics = function (d, b) {
22
- extendStatics = Object.setPrototypeOf ||
23
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
25
- return extendStatics(d, b);
26
- };
27
- return function (d, b) {
28
- extendStatics(d, b);
29
- function __() { this.constructor = d; }
30
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
31
- };
32
- })();
33
- var __assign = (this && this.__assign) || function () {
34
- __assign = Object.assign || function(t) {
35
- for (var s, i = 1, n = arguments.length; i < n; i++) {
36
- s = arguments[i];
37
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
38
- t[p] = s[p];
39
- }
40
- return t;
41
- };
42
- return __assign.apply(this, arguments);
43
- };
44
20
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
45
21
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
46
22
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -50,57 +26,20 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
50
26
  step((generator = generator.apply(thisArg, _arguments || [])).next());
51
27
  });
52
28
  };
53
- var __generator = (this && this.__generator) || function (thisArg, body) {
54
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
55
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
56
- function verb(n) { return function (v) { return step([n, v]); }; }
57
- function step(op) {
58
- if (f) throw new TypeError("Generator is already executing.");
59
- while (_) try {
60
- 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;
61
- if (y = 0, t) op = [op[0] & 2, t.value];
62
- switch (op[0]) {
63
- case 0: case 1: t = op; break;
64
- case 4: _.label++; return { value: op[1], done: false };
65
- case 5: _.label++; y = op[1]; op = [0]; continue;
66
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
67
- default:
68
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
69
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
70
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
71
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
72
- if (t[2]) _.ops.pop();
73
- _.trys.pop(); continue;
74
- }
75
- op = body.call(thisArg, _);
76
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
77
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
78
- }
79
- };
80
- var __spreadArrays = (this && this.__spreadArrays) || function () {
81
- for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
82
- for (var r = Array(s), k = 0, i = 0; i < il; i++)
83
- for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
84
- r[k] = a[j];
85
- return r;
86
- };
87
29
  Object.defineProperty(exports, "__esModule", { value: true });
88
30
  exports.BaseDB_ApiGenerator = exports.validator_InternationalPhoneNumber = exports.validator_LowerUpperStringWithDashesAndUnderscore = exports.validator_LowerUpperStringWithSpaces = exports.validator_LowercaseStringWithDashes = exports.validateNameWithDashesAndDots = exports.validator_JavaObjectMemberName = exports.validateStringAndNumbersWithDashes = exports.validateStringWithDashes = exports.validateOptionalId = exports.validateUniqueId = exports.validateGeneralUrl = exports.validateBucketUrl = exports.validateEmail = exports.validateId = void 0;
89
- var ts_common_1 = require("@intuitionrobotics/ts-common");
90
- var apis_1 = require("./apis");
91
- var backend_1 = require("@intuitionrobotics/thunderstorm/backend");
92
- var backend_2 = require("@intuitionrobotics/firebase/backend");
93
- var types_1 = require("../shared/types");
94
- var idLength = 32;
95
- var validateId = function (length, mandatory) {
96
- if (mandatory === void 0) { mandatory = true; }
97
- return ts_common_1.validateRegexp(new RegExp("^[0-9a-f]{" + length + "}$"), mandatory);
98
- };
31
+ const ts_common_1 = require("@intuitionrobotics/ts-common");
32
+ const apis_1 = require("./apis");
33
+ const backend_1 = require("@intuitionrobotics/thunderstorm/backend");
34
+ const backend_2 = require("@intuitionrobotics/firebase/backend");
35
+ const types_1 = require("../shared/types");
36
+ const idLength = 32;
37
+ const validateId = (length, mandatory = true) => ts_common_1.validateRegexp(new RegExp(`^[0-9a-f]{${length}}$`), mandatory);
99
38
  exports.validateId = validateId;
100
39
  exports.validateEmail = ts_common_1.validateRegexp(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/);
101
- var validateBucketUrl = function (mandatory) { return ts_common_1.validateRegexp(/gs?:\/\/[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/, mandatory); };
40
+ const validateBucketUrl = (mandatory) => ts_common_1.validateRegexp(/gs?:\/\/[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/, mandatory);
102
41
  exports.validateBucketUrl = validateBucketUrl;
103
- var validateGeneralUrl = function (mandatory) { return ts_common_1.validateRegexp(/[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/, mandatory); };
42
+ const validateGeneralUrl = (mandatory) => ts_common_1.validateRegexp(/[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/, mandatory);
104
43
  exports.validateGeneralUrl = validateGeneralUrl;
105
44
  exports.validateUniqueId = exports.validateId(idLength);
106
45
  exports.validateOptionalId = exports.validateId(idLength, false);
@@ -117,19 +56,17 @@ exports.validator_InternationalPhoneNumber = ts_common_1.validateRegexp(/^\+(?:[
117
56
  *
118
57
  * By default, it exposes API endpoints for creating, deleting, updating, querying and querying for unique document.
119
58
  */
120
- var BaseDB_ApiGenerator = /** @class */ (function (_super) {
121
- __extends(BaseDB_ApiGenerator, _super);
122
- function BaseDB_ApiGenerator(collectionName, validator, itemName) {
123
- var _this = _super.call(this) || this;
59
+ class BaseDB_ApiGenerator extends ts_common_1.Module {
60
+ constructor(collectionName, validator, itemName) {
61
+ super();
124
62
  // @ts-ignore
125
- _this.setDefaultConfig({ itemName: itemName, collectionName: collectionName, externalFilterKeys: ["_id"], lockKeys: ["_id"] });
126
- _this.validator = validator;
127
- return _this;
63
+ this.setDefaultConfig({ itemName, collectionName, externalFilterKeys: ["_id"], lockKeys: ["_id"] });
64
+ this.validator = validator;
128
65
  }
129
- BaseDB_ApiGenerator.prototype.setValidator = function (validator) {
66
+ setValidator(validator) {
130
67
  this.validator = validator;
131
- };
132
- BaseDB_ApiGenerator.prototype.__onFirestoreBackupSchedulerAct = function () {
68
+ }
69
+ __onFirestoreBackupSchedulerAct() {
133
70
  return [{
134
71
  backupQuery: this.resolveBackupQuery(),
135
72
  collection: this.collection,
@@ -137,10 +74,10 @@ var BaseDB_ApiGenerator = /** @class */ (function (_super) {
137
74
  interval: ts_common_1.Day,
138
75
  moduleKey: this.config.collectionName
139
76
  }];
140
- };
141
- BaseDB_ApiGenerator.prototype.resolveBackupQuery = function () {
77
+ }
78
+ resolveBackupQuery() {
142
79
  return { where: {} };
143
- };
80
+ }
144
81
  // this.setExternalUniqueKeys(["accessLevelIds"]);
145
82
  /**
146
83
  * Sets the external unique keys. External keys are the attributes of a document that must be unique inside the
@@ -154,11 +91,11 @@ var BaseDB_ApiGenerator = /** @class */ (function (_super) {
154
91
  * @returns
155
92
  * The external filter keys.
156
93
  */
157
- BaseDB_ApiGenerator.prototype.setExternalUniqueKeys = function (keys) {
94
+ setExternalUniqueKeys(keys) {
158
95
  if (this.initiated)
159
96
  throw new ts_common_1.BadImplementationException("You can only update the 'externalUniqueKeys' before the module was initialized.. preferably from its constructor");
160
97
  return this.config.externalFilterKeys = keys;
161
- };
98
+ }
162
99
  /**
163
100
  * Sets the lock keys. Lock keys are the attributes of a document that must not be changed during a patch.
164
101
  * Thr property `_id` is always part of the lock keys.
@@ -171,44 +108,38 @@ var BaseDB_ApiGenerator = /** @class */ (function (_super) {
171
108
  * @returns
172
109
  * The lock keys.
173
110
  */
174
- BaseDB_ApiGenerator.prototype.setLockKeys = function (keys) {
111
+ setLockKeys(keys) {
175
112
  if (this.initiated)
176
113
  throw new ts_common_1.BadImplementationException("You can only update the 'lockKeys' before the module was initialized.. preferably from its constructor");
177
- return this.config.lockKeys = ts_common_1.filterDuplicates(__spreadArrays(keys, ["_id"]));
178
- };
179
- BaseDB_ApiGenerator.prototype.getCollectionName = function () {
114
+ return this.config.lockKeys = ts_common_1.filterDuplicates([...keys,
115
+ "_id"]);
116
+ }
117
+ getCollectionName() {
180
118
  return this.config.collectionName;
181
- };
182
- BaseDB_ApiGenerator.prototype.getItemName = function () {
119
+ }
120
+ getItemName() {
183
121
  return this.config.itemName;
184
- };
122
+ }
185
123
  /**
186
124
  * Executed during the initialization of the module.
187
125
  * The collection reference is set in this method.
188
126
  */
189
- BaseDB_ApiGenerator.prototype.init = function () {
127
+ init() {
190
128
  var _a;
191
- var firestore = backend_2.FirebaseModule.createAdminSession((_a = this.config) === null || _a === void 0 ? void 0 : _a.projectId).getFirestore();
129
+ const firestore = backend_2.FirebaseModule.createAdminSession((_a = this.config) === null || _a === void 0 ? void 0 : _a.projectId).getFirestore();
192
130
  // @ts-ignore
193
131
  this.collection = firestore.getCollection(this.config.collectionName, this.config.externalFilterKeys);
194
- };
195
- BaseDB_ApiGenerator.prototype.assertExternalQueryUnique = function (instance, transaction) {
196
- return __awaiter(this, void 0, void 0, function () {
197
- var dbInstance, uniqueQuery;
198
- return __generator(this, function (_a) {
199
- switch (_a.label) {
200
- case 0: return [4 /*yield*/, transaction.queryItem(this.collection, instance)];
201
- case 1:
202
- dbInstance = _a.sent();
203
- if (!dbInstance) {
204
- uniqueQuery = backend_2.FirestoreInterface.buildUniqueQuery(this.collection, instance);
205
- throw new backend_1.ApiException(404, "Could not find " + this.config.itemName + " with unique query '" + ts_common_1.__stringify(uniqueQuery) + "'");
206
- }
207
- return [2 /*return*/, dbInstance];
208
- }
209
- });
132
+ }
133
+ assertExternalQueryUnique(instance, transaction) {
134
+ return __awaiter(this, void 0, void 0, function* () {
135
+ const dbInstance = yield transaction.queryItem(this.collection, instance);
136
+ if (!dbInstance) {
137
+ const uniqueQuery = backend_2.FirestoreInterface.buildUniqueQuery(this.collection, instance);
138
+ throw new backend_1.ApiException(404, `Could not find ${this.config.itemName} with unique query '${ts_common_1.__stringify(uniqueQuery)}'`);
139
+ }
140
+ return dbInstance;
210
141
  });
211
- };
142
+ }
212
143
  /**
213
144
  * Asserts the uniqueness of an instance in two steps:
214
145
  * - Executes `this.preUpsertProcessing`.
@@ -217,43 +148,28 @@ var BaseDB_ApiGenerator = /** @class */ (function (_super) {
217
148
  * @param transaction - The transaction object.
218
149
  * @param instance - The document for which the uniqueness assertion will occur.
219
150
  */
220
- BaseDB_ApiGenerator.prototype.assertUniqueness = function (transaction, instance, request) {
221
- return __awaiter(this, void 0, void 0, function () {
222
- var uniqueQueries, dbInstances, _loop_1, this_1, idx;
223
- var _this = this;
224
- return __generator(this, function (_a) {
225
- switch (_a.label) {
226
- case 0: return [4 /*yield*/, this.preUpsertProcessing(transaction, instance, request)];
227
- case 1:
228
- _a.sent();
229
- uniqueQueries = this.internalFilter(instance);
230
- if (uniqueQueries.length === 0)
231
- return [2 /*return*/];
232
- return [4 /*yield*/, Promise.all(uniqueQueries.map(function (uniqueQuery) {
233
- return transaction.queryUnique(_this.collection, { where: uniqueQuery });
234
- }))];
235
- case 2:
236
- dbInstances = _a.sent();
237
- _loop_1 = function (idx) {
238
- var dbInstance = dbInstances[idx];
239
- if (!dbInstance || dbInstance._id === instance._id)
240
- return "continue";
241
- var query = uniqueQueries[idx];
242
- var message = ts_common_1._keys(query).reduce(function (carry, key) {
243
- return carry + "\n" + (key + ": " + query[key]);
244
- }, this_1.config.itemName + " uniqueness violation. There is already a document with");
245
- this_1.logWarning(message);
246
- throw new backend_1.ApiException(422, message);
247
- };
248
- this_1 = this;
249
- for (idx in dbInstances) {
250
- _loop_1(idx);
251
- }
252
- return [2 /*return*/];
253
- }
254
- });
151
+ assertUniqueness(transaction, instance, request) {
152
+ return __awaiter(this, void 0, void 0, function* () {
153
+ yield this.preUpsertProcessing(transaction, instance, request);
154
+ const uniqueQueries = this.internalFilter(instance);
155
+ if (uniqueQueries.length === 0)
156
+ return;
157
+ const dbInstances = yield Promise.all(uniqueQueries.map(uniqueQuery => {
158
+ return transaction.queryUnique(this.collection, { where: uniqueQuery });
159
+ }));
160
+ for (const idx in dbInstances) {
161
+ const dbInstance = dbInstances[idx];
162
+ if (!dbInstance || dbInstance._id === instance._id)
163
+ continue;
164
+ const query = uniqueQueries[idx];
165
+ const message = ts_common_1._keys(query).reduce((carry, key) => {
166
+ return carry + "\n" + `${key}: ${query[key]}`;
167
+ }, `${this.config.itemName} uniqueness violation. There is already a document with`);
168
+ this.logWarning(message);
169
+ throw new backend_1.ApiException(422, message);
170
+ }
255
171
  });
256
- };
172
+ }
257
173
  /**
258
174
  * Runs the module's validator for the instance.
259
175
  *
@@ -261,55 +177,42 @@ var BaseDB_ApiGenerator = /** @class */ (function (_super) {
261
177
  *
262
178
  * @throws `ApiException` for bad implementation or invalid input.
263
179
  */
264
- BaseDB_ApiGenerator.prototype.validateImpl = function (instance) {
265
- return __awaiter(this, void 0, void 0, function () {
266
- var e_1, badImplementation, error, errorBody;
267
- return __generator(this, function (_a) {
268
- switch (_a.label) {
269
- case 0:
270
- _a.trys.push([0, 2, , 3]);
271
- return [4 /*yield*/, ts_common_1.validate(instance, this.validator)];
272
- case 1:
273
- _a.sent();
274
- return [3 /*break*/, 3];
275
- case 2:
276
- e_1 = _a.sent();
277
- badImplementation = ts_common_1.isErrorOfType(e_1, ts_common_1.BadImplementationException);
278
- if (badImplementation)
279
- throw new backend_1.ApiException(500, badImplementation.message);
280
- error = ts_common_1.isErrorOfType(e_1, ts_common_1.ValidationException);
281
- if (error) {
282
- errorBody = { type: types_1.ErrorKey_BadInput, body: { path: error.path, input: error.input } };
283
- throw new backend_1.ApiException(400, error.message).setErrorBody(errorBody);
284
- }
285
- return [3 /*break*/, 3];
286
- case 3: return [2 /*return*/];
180
+ validateImpl(instance) {
181
+ return __awaiter(this, void 0, void 0, function* () {
182
+ try {
183
+ yield ts_common_1.validate(instance, this.validator);
184
+ }
185
+ catch (e) {
186
+ const badImplementation = ts_common_1.isErrorOfType(e, ts_common_1.BadImplementationException);
187
+ if (badImplementation)
188
+ throw new backend_1.ApiException(500, badImplementation.message);
189
+ const error = ts_common_1.isErrorOfType(e, ts_common_1.ValidationException);
190
+ if (error) {
191
+ const errorBody = { type: types_1.ErrorKey_BadInput, body: { path: error.path, input: error.input } };
192
+ throw new backend_1.ApiException(400, error.message).setErrorBody(errorBody);
287
193
  }
288
- });
194
+ }
289
195
  });
290
- };
196
+ }
291
197
  /**
292
198
  * Override this method to return a list of "where" queries that dictate uniqueness inside the collection.
293
199
  * Example return value: [{attribute1: item.attribute1, attribute2: item.attribute2}].
294
200
  *
295
201
  * @param item - The DB entry that will be used.
296
202
  */
297
- BaseDB_ApiGenerator.prototype.internalFilter = function (item) {
203
+ internalFilter(item) {
298
204
  return [];
299
- };
205
+ }
300
206
  /**
301
207
  * Override this method to customize the assertions that should be done before the insertion of the document to the DB.
302
208
  *
303
209
  * @param transaction - The transaction object.
304
210
  * @param dbInstance - The DB entry for which the uniqueness is being asserted.
305
211
  */
306
- BaseDB_ApiGenerator.prototype.preUpsertProcessing = function (transaction, dbInstance, request) {
307
- return __awaiter(this, void 0, void 0, function () {
308
- return __generator(this, function (_a) {
309
- return [2 /*return*/];
310
- });
212
+ preUpsertProcessing(transaction, dbInstance, request) {
213
+ return __awaiter(this, void 0, void 0, function* () {
311
214
  });
312
- };
215
+ }
313
216
  /**
314
217
  * Override this method to provide actions or assertions to be executed before the deletion happens.
315
218
  *
@@ -318,28 +221,17 @@ var BaseDB_ApiGenerator = /** @class */ (function (_super) {
318
221
  * @param transaction - The transaction object
319
222
  * @param dbInstance - The DB entry that is going to be deleted.
320
223
  */
321
- BaseDB_ApiGenerator.prototype.assertDeletion = function (transaction, dbInstance, request) {
322
- return __awaiter(this, void 0, void 0, function () {
323
- return __generator(this, function (_a) {
324
- switch (_a.label) {
325
- case 0: return [4 /*yield*/, this.assertDeletion_Read(transaction, dbInstance, request)];
326
- case 1: return [2 /*return*/, (_a.sent())()];
327
- }
328
- });
224
+ assertDeletion(transaction, dbInstance, request) {
225
+ return __awaiter(this, void 0, void 0, function* () {
226
+ return (yield this.assertDeletion_Read(transaction, dbInstance, request))();
329
227
  });
330
- };
331
- BaseDB_ApiGenerator.prototype.assertDeletion_Read = function (transaction, dbInstance, request) {
332
- return __awaiter(this, void 0, void 0, function () {
333
- var _this = this;
334
- return __generator(this, function (_a) {
335
- return [2 /*return*/, function () { return __awaiter(_this, void 0, void 0, function () {
336
- return __generator(this, function (_a) {
337
- return [2 /*return*/];
338
- });
339
- }); }];
228
+ }
229
+ assertDeletion_Read(transaction, dbInstance, request) {
230
+ return __awaiter(this, void 0, void 0, function* () {
231
+ return () => __awaiter(this, void 0, void 0, function* () {
340
232
  });
341
233
  });
342
- };
234
+ }
343
235
  /**
344
236
  * A wrapper of the collections's `runInTransaction`.
345
237
  *
@@ -348,26 +240,17 @@ var BaseDB_ApiGenerator = /** @class */ (function (_super) {
348
240
  * @returns
349
241
  * A promise of the result of the `processor`.
350
242
  */
351
- BaseDB_ApiGenerator.prototype.runInTransaction = function (processor) {
352
- return __awaiter(this, void 0, void 0, function () {
353
- return __generator(this, function (_a) {
354
- return [2 /*return*/, this.collection.runInTransaction(processor)];
355
- });
243
+ runInTransaction(processor) {
244
+ return __awaiter(this, void 0, void 0, function* () {
245
+ return this.collection.runInTransaction(processor);
356
246
  });
357
- };
247
+ }
358
248
  // @ts-ignore
359
- BaseDB_ApiGenerator.prototype.deleteCollection = function () {
360
- return __awaiter(this, void 0, void 0, function () {
361
- return __generator(this, function (_a) {
362
- switch (_a.label) {
363
- case 0: return [4 /*yield*/, this.collection.deleteAll()];
364
- case 1:
365
- _a.sent();
366
- return [2 /*return*/];
367
- }
368
- });
249
+ deleteCollection() {
250
+ return __awaiter(this, void 0, void 0, function* () {
251
+ yield this.collection.deleteAll();
369
252
  });
370
- };
253
+ }
371
254
  /**
372
255
  * Inserts the `instance` using the `transaction` object.
373
256
  *
@@ -381,24 +264,13 @@ var BaseDB_ApiGenerator = /** @class */ (function (_super) {
381
264
  // private async createImpl(transaction: FirestoreTransaction, instance: DBType, request?: ExpressRequest): Promise<DBType> {
382
265
  // return (await this.createImpl_Read(transaction, instance, request))()
383
266
  // };
384
- BaseDB_ApiGenerator.prototype.createImpl_Read = function (transaction, instance, request) {
385
- return __awaiter(this, void 0, void 0, function () {
386
- var _this = this;
387
- return __generator(this, function (_a) {
388
- switch (_a.label) {
389
- case 0: return [4 /*yield*/, this.validateImpl(instance)];
390
- case 1:
391
- _a.sent();
392
- return [4 /*yield*/, this.assertUniqueness(transaction, instance, request)];
393
- case 2:
394
- _a.sent();
395
- return [2 /*return*/, function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
396
- return [2 /*return*/, transaction.insert(this.collection, instance)];
397
- }); }); }];
398
- }
399
- });
267
+ createImpl_Read(transaction, instance, request) {
268
+ return __awaiter(this, void 0, void 0, function* () {
269
+ yield this.validateImpl(instance);
270
+ yield this.assertUniqueness(transaction, instance, request);
271
+ return () => __awaiter(this, void 0, void 0, function* () { return transaction.insert(this.collection, instance); });
400
272
  });
401
- };
273
+ }
402
274
  ;
403
275
  /**
404
276
  * Upserts the `instance` using a transaction, after validating it and asserting uniqueness.
@@ -410,34 +282,23 @@ var BaseDB_ApiGenerator = /** @class */ (function (_super) {
410
282
  * @returns
411
283
  * A promise of the document that was upserted.
412
284
  */
413
- BaseDB_ApiGenerator.prototype.upsert = function (instance, transaction, request) {
414
- return __awaiter(this, void 0, void 0, function () {
415
- var processor;
416
- var _this = this;
417
- return __generator(this, function (_a) {
418
- processor = function (_transaction) { return __awaiter(_this, void 0, void 0, function () {
419
- return __generator(this, function (_a) {
420
- switch (_a.label) {
421
- case 0: return [4 /*yield*/, this.upsert_Read(instance, _transaction, request)];
422
- case 1: return [2 /*return*/, (_a.sent())()];
423
- }
424
- });
425
- }); };
426
- if (transaction)
427
- return [2 /*return*/, processor(transaction)];
428
- return [2 /*return*/, this.collection.runInTransaction(processor)];
285
+ upsert(instance, transaction, request) {
286
+ return __awaiter(this, void 0, void 0, function* () {
287
+ const processor = (_transaction) => __awaiter(this, void 0, void 0, function* () {
288
+ return (yield this.upsert_Read(instance, _transaction, request))();
429
289
  });
290
+ if (transaction)
291
+ return processor(transaction);
292
+ return this.collection.runInTransaction(processor);
430
293
  });
431
- };
432
- BaseDB_ApiGenerator.prototype.upsert_Read = function (instance, transaction, request) {
433
- return __awaiter(this, void 0, void 0, function () {
434
- return __generator(this, function (_a) {
435
- if (instance._id === undefined)
436
- return [2 /*return*/, this.createImpl_Read(transaction, __assign(__assign({}, instance), { _id: ts_common_1.generateHex(idLength) }), request)];
437
- return [2 /*return*/, this.upsertImpl_Read(transaction, instance, request)];
438
- });
294
+ }
295
+ upsert_Read(instance, transaction, request) {
296
+ return __awaiter(this, void 0, void 0, function* () {
297
+ if (instance._id === undefined)
298
+ return this.createImpl_Read(transaction, Object.assign(Object.assign({}, instance), { _id: ts_common_1.generateHex(idLength) }), request);
299
+ return this.upsertImpl_Read(transaction, instance, request);
439
300
  });
440
- };
301
+ }
441
302
  /**
442
303
  * Upserts a set of objects. Batching is used to circumvent firestore limitations on the number of objects.
443
304
  *
@@ -447,16 +308,11 @@ var BaseDB_ApiGenerator = /** @class */ (function (_super) {
447
308
  * @returns
448
309
  * A promise of an array of documents that were upserted.
449
310
  */
450
- BaseDB_ApiGenerator.prototype.upsertAll_Batched = function (instances, request) {
451
- return __awaiter(this, void 0, void 0, function () {
452
- var _this = this;
453
- return __generator(this, function (_a) {
454
- return [2 /*return*/, ts_common_1.batchAction(instances, 500, function (chunked) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
455
- return [2 /*return*/, this.upsertAll(chunked, undefined, request)];
456
- }); }); })];
457
- });
311
+ upsertAll_Batched(instances, request) {
312
+ return __awaiter(this, void 0, void 0, function* () {
313
+ return ts_common_1.batchAction(instances, 500, (chunked) => __awaiter(this, void 0, void 0, function* () { return this.upsertAll(chunked, undefined, request); }));
458
314
  });
459
- };
315
+ }
460
316
  /**
461
317
  * Upserts the `dbInstances` using the `transaction` object.
462
318
  *
@@ -469,50 +325,32 @@ var BaseDB_ApiGenerator = /** @class */ (function (_super) {
469
325
  * @returns
470
326
  * A promise of the array of documents that were upserted.
471
327
  */
472
- BaseDB_ApiGenerator.prototype.upsertAll = function (instances, transaction, request) {
473
- return __awaiter(this, void 0, void 0, function () {
474
- var processor;
475
- var _this = this;
476
- return __generator(this, function (_a) {
477
- if (instances.length > 500) {
478
- if (transaction)
479
- throw new ts_common_1.BadImplementationException('Firestore transaction supports maximum 500 at a time');
480
- return [2 /*return*/, this.upsertAll_Batched(instances, request)];
481
- }
482
- processor = function (_transaction) { return __awaiter(_this, void 0, void 0, function () {
483
- var writes, _a, _b;
484
- return __generator(this, function (_c) {
485
- switch (_c.label) {
486
- case 0:
487
- _b = (_a = Promise).all;
488
- return [4 /*yield*/, this.upsertAllImpl_Read(instances, _transaction, request)];
489
- case 1: return [4 /*yield*/, _b.apply(_a, [_c.sent()])];
490
- case 2:
491
- writes = _c.sent();
492
- return [2 /*return*/, Promise.all(writes.map(function (write) { return write(); }))];
493
- }
494
- });
495
- }); };
328
+ upsertAll(instances, transaction, request) {
329
+ return __awaiter(this, void 0, void 0, function* () {
330
+ if (instances.length > 500) {
496
331
  if (transaction)
497
- return [2 /*return*/, processor(transaction)];
498
- return [2 /*return*/, this.collection.runInTransaction(processor)];
332
+ throw new ts_common_1.BadImplementationException('Firestore transaction supports maximum 500 at a time');
333
+ return this.upsertAll_Batched(instances, request);
334
+ }
335
+ const processor = (_transaction) => __awaiter(this, void 0, void 0, function* () {
336
+ const writes = yield Promise.all(yield this.upsertAllImpl_Read(instances, _transaction, request));
337
+ return Promise.all(writes.map(write => write()));
499
338
  });
339
+ if (transaction)
340
+ return processor(transaction);
341
+ return this.collection.runInTransaction(processor);
500
342
  });
501
- };
502
- BaseDB_ApiGenerator.prototype.upsertAllImpl_Read = function (instances, transaction, request) {
503
- return __awaiter(this, void 0, void 0, function () {
504
- var actions;
505
- var _this = this;
506
- return __generator(this, function (_a) {
507
- actions = [];
508
- instances.reduce(function (carry, instance) {
509
- ts_common_1.addItemToArray(carry, _this.upsert_Read(instance, transaction, request));
510
- return carry;
511
- }, actions);
512
- return [2 /*return*/, Promise.all(actions)];
513
- });
343
+ }
344
+ upsertAllImpl_Read(instances, transaction, request) {
345
+ return __awaiter(this, void 0, void 0, function* () {
346
+ const actions = [];
347
+ instances.reduce((carry, instance) => {
348
+ ts_common_1.addItemToArray(carry, this.upsert_Read(instance, transaction, request));
349
+ return carry;
350
+ }, actions);
351
+ return Promise.all(actions);
514
352
  });
515
- };
353
+ }
516
354
  /**
517
355
  * Upserts the `dbInstance` using the `transaction` transaction object.
518
356
  *
@@ -523,32 +361,19 @@ var BaseDB_ApiGenerator = /** @class */ (function (_super) {
523
361
  * @returns
524
362
  * A promise of the document that was upserted.
525
363
  */
526
- BaseDB_ApiGenerator.prototype.upsertImpl = function (transaction, dbInstance, request) {
527
- return __awaiter(this, void 0, void 0, function () {
528
- return __generator(this, function (_a) {
529
- switch (_a.label) {
530
- case 0: return [4 /*yield*/, this.upsertImpl_Read(transaction, dbInstance, request)];
531
- case 1: return [2 /*return*/, (_a.sent())()];
532
- }
533
- });
364
+ upsertImpl(transaction, dbInstance, request) {
365
+ return __awaiter(this, void 0, void 0, function* () {
366
+ return (yield this.upsertImpl_Read(transaction, dbInstance, request))();
534
367
  });
535
- };
368
+ }
536
369
  ;
537
- BaseDB_ApiGenerator.prototype.upsertImpl_Read = function (transaction, dbInstance, request) {
538
- return __awaiter(this, void 0, void 0, function () {
539
- return __generator(this, function (_a) {
540
- switch (_a.label) {
541
- case 0: return [4 /*yield*/, this.validateImpl(dbInstance)];
542
- case 1:
543
- _a.sent();
544
- return [4 /*yield*/, this.assertUniqueness(transaction, dbInstance, request)];
545
- case 2:
546
- _a.sent();
547
- return [2 /*return*/, transaction.upsert_Read(this.collection, dbInstance)];
548
- }
549
- });
370
+ upsertImpl_Read(transaction, dbInstance, request) {
371
+ return __awaiter(this, void 0, void 0, function* () {
372
+ yield this.validateImpl(dbInstance);
373
+ yield this.assertUniqueness(transaction, dbInstance, request);
374
+ return transaction.upsert_Read(this.collection, dbInstance);
550
375
  });
551
- };
376
+ }
552
377
  ;
553
378
  /**
554
379
  * Deletes a unique document based on its `_id`. Uses a transaction, after deletion assertions occur.
@@ -562,69 +387,39 @@ var BaseDB_ApiGenerator = /** @class */ (function (_super) {
562
387
  * @returns
563
388
  * A promise of the document that was deleted.
564
389
  */
565
- BaseDB_ApiGenerator.prototype.deleteUnique = function (_id, transaction, request) {
566
- return __awaiter(this, void 0, void 0, function () {
567
- var processor;
568
- var _this = this;
569
- return __generator(this, function (_a) {
570
- if (!_id)
571
- throw new ts_common_1.BadImplementationException("No _id for deletion provided.");
572
- processor = function (_transaction) { return __awaiter(_this, void 0, void 0, function () {
573
- var write;
574
- return __generator(this, function (_a) {
575
- switch (_a.label) {
576
- case 0: return [4 /*yield*/, this.deleteUnique_Read(_id, _transaction, request)];
577
- case 1:
578
- write = _a.sent();
579
- if (!write)
580
- throw new backend_1.ApiException(404, "Could not find " + this.config.itemName + " with unique id: " + _id);
581
- return [2 /*return*/, write()];
582
- }
583
- });
584
- }); };
585
- if (transaction)
586
- return [2 /*return*/, processor(transaction)];
587
- return [2 /*return*/, this.collection.runInTransaction(processor)];
390
+ deleteUnique(_id, transaction, request) {
391
+ return __awaiter(this, void 0, void 0, function* () {
392
+ if (!_id)
393
+ throw new ts_common_1.BadImplementationException(`No _id for deletion provided.`);
394
+ const processor = (_transaction) => __awaiter(this, void 0, void 0, function* () {
395
+ const write = yield this.deleteUnique_Read(_id, _transaction, request);
396
+ if (!write)
397
+ throw new backend_1.ApiException(404, `Could not find ${this.config.itemName} with unique id: ${_id}`);
398
+ return write();
588
399
  });
400
+ if (transaction)
401
+ return processor(transaction);
402
+ return this.collection.runInTransaction(processor);
589
403
  });
590
- };
591
- BaseDB_ApiGenerator.prototype.deleteUnique_Read = function (_id, transaction, request) {
592
- return __awaiter(this, void 0, void 0, function () {
593
- var ourQuery, dbInstance, write;
594
- var _this = this;
595
- return __generator(this, function (_a) {
596
- switch (_a.label) {
597
- case 0:
598
- if (!_id)
599
- throw new ts_common_1.BadImplementationException("No _id for deletion provided.");
600
- ourQuery = { where: { _id: _id } };
601
- return [4 /*yield*/, transaction.queryUnique(this.collection, ourQuery)];
602
- case 1:
603
- dbInstance = _a.sent();
604
- if (!dbInstance)
605
- throw new backend_1.ApiException(404, "Could not find " + this.config.itemName + " with unique id: " + _id);
606
- return [4 /*yield*/, this.deleteImpl_Read(transaction, ourQuery, request)];
607
- case 2:
608
- write = _a.sent();
609
- return [2 /*return*/, function () { return __awaiter(_this, void 0, void 0, function () {
610
- return __generator(this, function (_a) {
611
- switch (_a.label) {
612
- case 0:
613
- if (!write)
614
- return [2 /*return*/, dbInstance];
615
- // Here can do both read an write!
616
- return [4 /*yield*/, this.assertDeletion(transaction, dbInstance, request)];
617
- case 1:
618
- // Here can do both read an write!
619
- _a.sent();
620
- return [2 /*return*/, write()];
621
- }
622
- });
623
- }); }];
624
- }
404
+ }
405
+ deleteUnique_Read(_id, transaction, request) {
406
+ return __awaiter(this, void 0, void 0, function* () {
407
+ if (!_id)
408
+ throw new ts_common_1.BadImplementationException(`No _id for deletion provided.`);
409
+ const ourQuery = { where: { _id } };
410
+ const dbInstance = yield transaction.queryUnique(this.collection, ourQuery);
411
+ if (!dbInstance)
412
+ throw new backend_1.ApiException(404, `Could not find ${this.config.itemName} with unique id: ${_id}`);
413
+ const write = yield this.deleteImpl_Read(transaction, ourQuery, request);
414
+ return () => __awaiter(this, void 0, void 0, function* () {
415
+ if (!write)
416
+ return dbInstance;
417
+ // Here can do both read an write!
418
+ yield this.assertDeletion(transaction, dbInstance, request);
419
+ return write();
625
420
  });
626
421
  });
627
- };
422
+ }
628
423
  /**
629
424
  * Uses the `transaction` to delete a unique document, querying with the `ourQuery`.
630
425
  *
@@ -635,34 +430,25 @@ var BaseDB_ApiGenerator = /** @class */ (function (_super) {
635
430
  * @returns
636
431
  * A promise of the document that was deleted.
637
432
  */
638
- BaseDB_ApiGenerator.prototype.deleteImpl_Read = function (transaction, ourQuery, request) {
639
- return __awaiter(this, void 0, void 0, function () {
640
- var write;
641
- return __generator(this, function (_a) {
642
- switch (_a.label) {
643
- case 0: return [4 /*yield*/, transaction.deleteUnique_Read(this.collection, ourQuery)];
644
- case 1:
645
- write = _a.sent();
646
- if (!write)
647
- throw new ts_common_1.ThisShouldNotHappenException("I just checked that I had an instance for query: " + ts_common_1.__stringify(ourQuery));
648
- return [2 /*return*/, write];
649
- }
650
- });
433
+ deleteImpl_Read(transaction, ourQuery, request) {
434
+ return __awaiter(this, void 0, void 0, function* () {
435
+ const write = yield transaction.deleteUnique_Read(this.collection, ourQuery);
436
+ if (!write)
437
+ throw new ts_common_1.ThisShouldNotHappenException(`I just checked that I had an instance for query: ${ts_common_1.__stringify(ourQuery)}`);
438
+ return write;
651
439
  });
652
- };
440
+ }
653
441
  /**
654
442
  * Calls the `delete` method of the module's collection.
655
443
  *
656
444
  * @param query - The query to be executed for the deletion.
657
445
  * @param request - The request in order to possibly obtain more info.
658
446
  */
659
- BaseDB_ApiGenerator.prototype.delete = function (query, request) {
660
- return __awaiter(this, void 0, void 0, function () {
661
- return __generator(this, function (_a) {
662
- return [2 /*return*/, this.collection.delete(query)];
663
- });
447
+ delete(query, request) {
448
+ return __awaiter(this, void 0, void 0, function* () {
449
+ return this.collection.delete(query);
664
450
  });
665
- };
451
+ }
666
452
  /**
667
453
  * Queries the database for a specific document in the module's collection.
668
454
  *
@@ -674,21 +460,14 @@ var BaseDB_ApiGenerator = /** @class */ (function (_super) {
674
460
  * @returns
675
461
  * The DB document that was found.
676
462
  */
677
- BaseDB_ApiGenerator.prototype.queryUnique = function (where, request) {
678
- return __awaiter(this, void 0, void 0, function () {
679
- var dbItem;
680
- return __generator(this, function (_a) {
681
- switch (_a.label) {
682
- case 0: return [4 /*yield*/, this.collection.queryUnique({ where: where })];
683
- case 1:
684
- dbItem = _a.sent();
685
- if (!dbItem)
686
- throw new backend_1.ApiException(404, "Could not find " + this.config.itemName + " with unique query: " + JSON.stringify(where));
687
- return [2 /*return*/, dbItem];
688
- }
689
- });
463
+ queryUnique(where, request) {
464
+ return __awaiter(this, void 0, void 0, function* () {
465
+ const dbItem = yield this.collection.queryUnique({ where });
466
+ if (!dbItem)
467
+ throw new backend_1.ApiException(404, `Could not find ${this.config.itemName} with unique query: ${JSON.stringify(where)}`);
468
+ return dbItem;
690
469
  });
691
- };
470
+ }
692
471
  /**
693
472
  * Executes the specified query on the module's collection.
694
473
  *
@@ -698,16 +477,11 @@ var BaseDB_ApiGenerator = /** @class */ (function (_super) {
698
477
  * @returns
699
478
  * A promise of an array of documents.
700
479
  */
701
- BaseDB_ApiGenerator.prototype.query = function (query, request) {
702
- return __awaiter(this, void 0, void 0, function () {
703
- return __generator(this, function (_a) {
704
- switch (_a.label) {
705
- case 0: return [4 /*yield*/, this.collection.query(query)];
706
- case 1: return [2 /*return*/, _a.sent()];
707
- }
708
- });
480
+ query(query, request) {
481
+ return __awaiter(this, void 0, void 0, function* () {
482
+ return yield this.collection.query(query);
709
483
  });
710
- };
484
+ }
711
485
  /**
712
486
  * If propsToPatch is not set, we remove the lock keys from the caller's instance
713
487
  * before merging with the original dbInstance.
@@ -721,57 +495,43 @@ var BaseDB_ApiGenerator = /** @class */ (function (_super) {
721
495
  * @returns
722
496
  * A promise of the patched document.
723
497
  */
724
- BaseDB_ApiGenerator.prototype.patch = function (instance, propsToPatch, request) {
725
- return __awaiter(this, void 0, void 0, function () {
726
- var _this = this;
727
- return __generator(this, function (_a) {
728
- return [2 /*return*/, this.collection.runInTransaction(function (transaction) { return __awaiter(_this, void 0, void 0, function () {
729
- var dbInstance, wrongKey, mergedObject;
730
- var _this = this;
731
- return __generator(this, function (_a) {
732
- switch (_a.label) {
733
- case 0: return [4 /*yield*/, this.assertExternalQueryUnique(instance, transaction)];
734
- case 1:
735
- dbInstance = _a.sent();
736
- wrongKey = propsToPatch === null || propsToPatch === void 0 ? void 0 : propsToPatch.find(function (prop) { return _this.config.lockKeys.includes(prop); });
737
- if (wrongKey)
738
- throw new ts_common_1.BadImplementationException("Key " + wrongKey + " is part of the 'lockKeys' and cannot be updated.");
739
- // If the caller has not specified props, we remove the keys from the caller's instance
740
- // before merging with the original dbInstance.
741
- ts_common_1._keys(instance).forEach(function (key) {
742
- if (_this.config.lockKeys.includes(key) || (propsToPatch && !propsToPatch.includes(key))) {
743
- delete instance[key];
744
- }
745
- });
746
- mergedObject = ts_common_1.merge(dbInstance, instance);
747
- return [4 /*yield*/, ts_common_1.validate(mergedObject, this.validator)];
748
- case 2:
749
- _a.sent();
750
- return [4 /*yield*/, this.assertUniqueness(transaction, mergedObject, request)];
751
- case 3:
752
- _a.sent();
753
- return [2 /*return*/, this.upsertImpl(transaction, mergedObject, request)];
754
- }
755
- });
756
- }); })];
757
- });
498
+ patch(instance, propsToPatch, request) {
499
+ return __awaiter(this, void 0, void 0, function* () {
500
+ return this.collection.runInTransaction((transaction) => __awaiter(this, void 0, void 0, function* () {
501
+ const dbInstance = yield this.assertExternalQueryUnique(instance, transaction);
502
+ // If the caller has specified props to be changed, make sure the don't conflict with the lockKeys.
503
+ const wrongKey = propsToPatch === null || propsToPatch === void 0 ? void 0 : propsToPatch.find(prop => this.config.lockKeys.includes(prop));
504
+ if (wrongKey)
505
+ throw new ts_common_1.BadImplementationException(`Key ${wrongKey} is part of the 'lockKeys' and cannot be updated.`);
506
+ // If the caller has not specified props, we remove the keys from the caller's instance
507
+ // before merging with the original dbInstance.
508
+ ts_common_1._keys(instance).forEach(key => {
509
+ if (this.config.lockKeys.includes(key) || (propsToPatch && !propsToPatch.includes(key))) {
510
+ delete instance[key];
511
+ }
512
+ });
513
+ const mergedObject = ts_common_1.merge(dbInstance, instance);
514
+ yield ts_common_1.validate(mergedObject, this.validator);
515
+ yield this.assertUniqueness(transaction, mergedObject, request);
516
+ return this.upsertImpl(transaction, mergedObject, request);
517
+ }));
758
518
  });
759
- };
760
- BaseDB_ApiGenerator.prototype.apiCreate = function (pathPart) {
519
+ }
520
+ apiCreate(pathPart) {
761
521
  return new apis_1.ServerApi_Create(this, pathPart);
762
- };
763
- BaseDB_ApiGenerator.prototype.apiQuery = function (pathPart) {
522
+ }
523
+ apiQuery(pathPart) {
764
524
  return new apis_1.ServerApi_Query(this, pathPart);
765
- };
766
- BaseDB_ApiGenerator.prototype.apiQueryUnique = function (pathPart) {
525
+ }
526
+ apiQueryUnique(pathPart) {
767
527
  return new apis_1.ServerApi_Unique(this, pathPart);
768
- };
769
- BaseDB_ApiGenerator.prototype.apiUpdate = function (pathPart) {
528
+ }
529
+ apiUpdate(pathPart) {
770
530
  return new apis_1.ServerApi_Update(this, pathPart);
771
- };
772
- BaseDB_ApiGenerator.prototype.apiDelete = function (pathPart) {
531
+ }
532
+ apiDelete(pathPart) {
773
533
  return new apis_1.ServerApi_Delete(this, pathPart);
774
- };
534
+ }
775
535
  /**
776
536
  * Override this method, to control which server api endpoints are created automatically.
777
537
  *
@@ -780,7 +540,7 @@ var BaseDB_ApiGenerator = /** @class */ (function (_super) {
780
540
  * @returns
781
541
  * An array of api endpoints.
782
542
  */
783
- BaseDB_ApiGenerator.prototype.apis = function (pathPart) {
543
+ apis(pathPart) {
784
544
  return ts_common_1.filterInstances([
785
545
  this.apiCreate(pathPart),
786
546
  this.apiQuery(pathPart),
@@ -788,8 +548,7 @@ var BaseDB_ApiGenerator = /** @class */ (function (_super) {
788
548
  this.apiUpdate(pathPart),
789
549
  this.apiDelete(pathPart),
790
550
  ]);
791
- };
792
- return BaseDB_ApiGenerator;
793
- }(ts_common_1.Module));
551
+ }
552
+ }
794
553
  exports.BaseDB_ApiGenerator = BaseDB_ApiGenerator;
795
554
  //# sourceMappingURL=BaseDB_ApiGenerator.js.map