blixify-server 0.3.29 → 1.0.0

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.
Files changed (37) hide show
  1. package/dist/apis/authWrapper.d.ts.map +1 -1
  2. package/dist/apis/authWrapper.js +1 -228
  3. package/dist/apis/crypto.d.ts.map +1 -1
  4. package/dist/apis/crypto.js +1 -63
  5. package/dist/apis/dayjs.d.ts +3 -0
  6. package/dist/apis/dayjs.d.ts.map +1 -0
  7. package/dist/apis/dayjs.js +1 -0
  8. package/dist/apis/fbWrapper.d.ts +6 -6
  9. package/dist/apis/fbWrapper.d.ts.map +1 -1
  10. package/dist/apis/fbWrapper.js +1 -839
  11. package/dist/apis/googleAnalyticsWrapper.d.ts.map +1 -1
  12. package/dist/apis/googleAnalyticsWrapper.js +1 -223
  13. package/dist/apis/index.js +1 -21
  14. package/dist/apis/mondayWrapper.d.ts +2 -2
  15. package/dist/apis/mondayWrapper.d.ts.map +1 -1
  16. package/dist/apis/mondayWrapper.js +32 -527
  17. package/dist/apis/mongoWrapper.d.ts +6 -6
  18. package/dist/apis/mongoWrapper.d.ts.map +1 -1
  19. package/dist/apis/mongoWrapper.js +1 -1526
  20. package/dist/apis/postgresqlWrapper.d.ts +3 -3
  21. package/dist/apis/postgresqlWrapper.d.ts.map +1 -1
  22. package/dist/apis/postgresqlWrapper.js +1 -514
  23. package/dist/apis/security.d.ts.map +1 -1
  24. package/dist/apis/security.js +1 -80
  25. package/dist/apis/trackVisionWrapper.d.ts.map +1 -1
  26. package/dist/apis/trackVisionWrapper.js +1 -150
  27. package/dist/apis/uploadWrapper.d.ts.map +1 -1
  28. package/dist/apis/uploadWrapper.js +1 -481
  29. package/dist/apis/utils.d.ts +1 -1
  30. package/dist/apis/utils.d.ts.map +1 -1
  31. package/dist/apis/utils.js +1 -25
  32. package/dist/buildtsconfig.tsbuildinfo +1 -0
  33. package/dist/model/Log.js +1 -2
  34. package/dist/model/QueryModel.d.ts.map +1 -1
  35. package/dist/model/QueryModel.js +1 -118
  36. package/dist/model/SecurityConfig.js +1 -2
  37. package/package.json +21 -12
@@ -1,839 +1 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.FirebaseWrapper = void 0;
16
- const firestore_1 = require("firebase-admin/firestore");
17
- const moment_timezone_1 = __importDefault(require("moment-timezone"));
18
- const QueryModel_1 = require("../model/QueryModel");
19
- const utils_1 = require("./utils");
20
- /**
21
- * @Wrapper
22
- *
23
- */
24
- class FirebaseWrapper {
25
- constructor(fbAdmin, collection, isProd, config, modelChecker, lib) {
26
- this.fbAdmin = "";
27
- this.collection = "";
28
- this.isProd = false;
29
- this.config = {
30
- baseConfig: [],
31
- opsConfig: {
32
- read: [],
33
- create: [],
34
- update: [],
35
- delete: [],
36
- },
37
- };
38
- // eslint-disable-next-line
39
- this.modelChecker = (obj) => {
40
- return false;
41
- };
42
- this.parseModel = (data) => {
43
- delete data["id"];
44
- data["baseUpdatedAt"] = (0, moment_timezone_1.default)().toDate();
45
- return data;
46
- };
47
- this.initBatchCreate = (req, res, workflow) => __awaiter(this, void 0, void 0, function* () {
48
- try {
49
- const batch = this.fbAdmin.firestore().batch();
50
- const fbCollection = this.fbAdmin.firestore().collection(this.collection);
51
- if (Array.isArray(req.body.data)) {
52
- let valid = true;
53
- req.body.data.map((eachData) => {
54
- if (!this.modelChecker(eachData)) {
55
- valid = false;
56
- }
57
- });
58
- if (valid) {
59
- const dataList = req.body.data;
60
- const validBaseConfig = (0, QueryModel_1.checkBaseConfig)(this.config, req);
61
- let validOpsConfig = true;
62
- const ids = [];
63
- const uniqueDataListField = [];
64
- dataList.map((eachData) => {
65
- ids.push(eachData.id);
66
- if (!(0, QueryModel_1.checkOpsConfig)(this.config, "update", req, eachData)) {
67
- validOpsConfig = false;
68
- }
69
- if (req.body.unique && (eachData === null || eachData === void 0 ? void 0 : eachData[req.body.unique]))
70
- uniqueDataListField.push(eachData === null || eachData === void 0 ? void 0 : eachData[req.body.unique]);
71
- });
72
- if (!validBaseConfig || !validOpsConfig) {
73
- res.status(400).json({ err: "Invalid Security Configuration" });
74
- return;
75
- }
76
- if (uniqueDataListField.length > 0) {
77
- const existsDataSnapshot = yield fbCollection
78
- .find(req.body.unique, "in", uniqueDataListField)
79
- .get();
80
- const existsDataList = [];
81
- if (!existsDataSnapshot.empty) {
82
- existsDataSnapshot.forEach((eachDataDoc) => {
83
- const eachData = eachDataDoc.data();
84
- existsDataList.push(eachData);
85
- });
86
- }
87
- if (existsDataList.length > 0) {
88
- res.status(400).json({
89
- err: `Unique:${existsDataList.map((eachData) => eachData === null || eachData === void 0 ? void 0 : eachData[req.body.unique])} exists`,
90
- });
91
- return;
92
- }
93
- }
94
- if (workflow)
95
- yield workflow(dataList);
96
- yield Promise.all(dataList.map((eachData) => __awaiter(this, void 0, void 0, function* () {
97
- eachData["baseUpdatedAt"] = (0, moment_timezone_1.default)().toDate();
98
- const batchRef = fbCollection.doc(eachData["id"]);
99
- batch.set(batchRef, Object.assign({}, eachData));
100
- })));
101
- yield batch.commit();
102
- res.send({ success: ids });
103
- }
104
- else {
105
- res.status(400).json({ err: "Invalid Model Structure" });
106
- }
107
- }
108
- else {
109
- res.status(400).json({ err: "Invalid Fields" });
110
- }
111
- }
112
- catch (err) {
113
- res.status(400).json({ err: err });
114
- }
115
- });
116
- this.initCreate = (req, res, workflow) => __awaiter(this, void 0, void 0, function* () {
117
- var _a, _b;
118
- try {
119
- const valid = this.modelChecker(req.body.data);
120
- if (valid) {
121
- //INFO : Security Checker
122
- const validBaseConfig = (0, QueryModel_1.checkBaseConfig)(this.config, req);
123
- const validOpsConfig = (0, QueryModel_1.checkOpsConfig)(this.config, "create", req, req.body.data);
124
- if (!validBaseConfig || !validOpsConfig) {
125
- res.status(400).json({ err: "Invalid Security Configuration" });
126
- return;
127
- }
128
- const fbCollection = this.fbAdmin
129
- .firestore()
130
- .collection(this.collection);
131
- req.body.data["baseUpdatedAt"] = (0, moment_timezone_1.default)().toDate();
132
- if (req.body.unique && ((_a = req.body.data) === null || _a === void 0 ? void 0 : _a[req.body.unique])) {
133
- const querySnapshot = yield fbCollection
134
- .where(req.body.unique, "==", (_b = req.body.data) === null || _b === void 0 ? void 0 : _b[req.body.unique])
135
- .get();
136
- if (!querySnapshot.empty) {
137
- res
138
- .status(400)
139
- .json({ err: `Unique:${req.body.data[req.body.unique]} exists` });
140
- return;
141
- }
142
- }
143
- if (workflow)
144
- yield workflow(req.body.data);
145
- yield fbCollection.doc(req.body.data["id"]).set(req.body.data);
146
- res.send({ success: true });
147
- }
148
- else {
149
- res.status(400).json({ err: "Invalid Model Structure" });
150
- }
151
- }
152
- catch (err) {
153
- res.status(400).json({ err: err });
154
- }
155
- });
156
- this.initGet = (req, res) => __awaiter(this, void 0, void 0, function* () {
157
- try {
158
- const valid = req.body.id;
159
- if (valid) {
160
- //INFO : Security Checker
161
- const dataQuery = yield this.fbAdmin
162
- .firestore()
163
- .collection(this.collection)
164
- .doc(valid)
165
- .get();
166
- if (!dataQuery.exists) {
167
- res.status(400).json({ err: "Invalid Security Configuration" });
168
- return;
169
- }
170
- const fbData = dataQuery.data();
171
- const validBaseConfig = (0, QueryModel_1.checkBaseConfig)(this.config, req);
172
- const validOpsConfig = (0, QueryModel_1.checkOpsConfig)(this.config, "read", req, fbData);
173
- if (!validBaseConfig || !validOpsConfig) {
174
- res.status(400).json({ err: "Invalid Security Configuration" });
175
- return;
176
- }
177
- res.send({ data: fbData });
178
- }
179
- else {
180
- res.status(400).json({ err: "Invalid Fields" });
181
- }
182
- }
183
- catch (err) {
184
- res.status(400).json({ err: err });
185
- }
186
- });
187
- this.initBatchUpdate = (req, res, workflow) => __awaiter(this, void 0, void 0, function* () {
188
- var _c, _d;
189
- const batch = this.fbAdmin.firestore().batch();
190
- try {
191
- const valid = this.modelChecker(req.body.data) && req.body.query;
192
- const data = this.parseModel((_c = req.body.data) !== null && _c !== void 0 ? _c : []);
193
- const queryList = (_d = req.body.query) !== null && _d !== void 0 ? _d : [];
194
- const isOr = req.body.isOr || false; // Check if it's an OR query
195
- const unsetData = req.body.unsetData;
196
- if (valid) {
197
- const fbCollection = this.fbAdmin
198
- .firestore()
199
- .collection(this.collection);
200
- //INFO : Step 1 - Query
201
- const conditions = [];
202
- queryList.forEach((eachQuery) => {
203
- var _a;
204
- const queryId = (_a = eachQuery.queryId) !== null && _a !== void 0 ? _a : "";
205
- const value = eachQuery.value;
206
- switch (eachQuery.type) {
207
- case "=":
208
- conditions.push(this.fbAdmin.firestore.Filter.where(queryId, "==", value));
209
- break;
210
- case "!=":
211
- conditions.push(this.fbAdmin.firestore.Filter.where(queryId, "!=", value));
212
- break;
213
- case ">":
214
- conditions.push(this.fbAdmin.firestore.Filter.where(queryId, ">", value));
215
- break;
216
- case "<":
217
- conditions.push(this.fbAdmin.firestore.Filter.where(queryId, "<", value));
218
- break;
219
- case "><":
220
- if (Array.isArray(value) && value.length >= 2) {
221
- conditions.push(this.fbAdmin.firestore.Filter.where(queryId, ">=", value[0]), this.fbAdmin.firestore.Filter.where(queryId, "<=", value[1]));
222
- }
223
- break;
224
- case "in":
225
- conditions.push(this.fbAdmin.firestore.Filter.where(queryId, "in", value));
226
- break;
227
- default:
228
- break;
229
- }
230
- });
231
- // Construct the final query condition based on isOr
232
- const finalQueryCondition = isOr
233
- ? this.fbAdmin.firestore.Filter.or(...conditions)
234
- : this.fbAdmin.firestore.Filter.and(...conditions);
235
- const fbSnapshot = yield fbCollection.where(finalQueryCondition).get();
236
- const validBaseConfig = (0, QueryModel_1.checkBaseConfig)(this.config, req);
237
- //INFO : Security Checker
238
- let validOpsConfig = true;
239
- const workflowUpdateFieldsList = [];
240
- const filterDataIds = [];
241
- if (fbSnapshot) {
242
- fbSnapshot.forEach((eachDataDoc) => {
243
- const fbData = eachDataDoc.data();
244
- filterDataIds.push(fbData.id);
245
- if (req.body.sensitive) {
246
- if (!(0, moment_timezone_1.default)(req.body.data.baseUpdatedAt).isAfter((0, moment_timezone_1.default)(fbData.baseUpdatedAt.seconds * 1000))) {
247
- res.status(400).json({ err: "Refresh Sensitive Model" });
248
- }
249
- }
250
- if (!(0, QueryModel_1.checkOpsConfig)(this.config, "update", req, fbData)) {
251
- validOpsConfig = false;
252
- }
253
- const { workflowUpdateFields } = (0, utils_1.compareUpdatedFields)(eachDataDoc, req.body.data);
254
- workflowUpdateFieldsList.push(workflowUpdateFields);
255
- });
256
- }
257
- if (!validBaseConfig || !validOpsConfig) {
258
- res.status(400).json({ err: "Invalid Security Configuration" });
259
- return;
260
- }
261
- let condition = {};
262
- if (unsetData) {
263
- unsetData.forEach((eachField) => {
264
- condition[eachField] = this.fbAdmin.firestore.FieldValue.delete();
265
- });
266
- }
267
- if (data) {
268
- condition = Object.assign(Object.assign({}, data), condition);
269
- }
270
- if (workflow)
271
- yield workflow(workflowUpdateFieldsList);
272
- yield Promise.all(filterDataIds.map((eachId) => {
273
- const batchRef = this.fbAdmin
274
- .firestore()
275
- .collection(this.collection)
276
- .doc(eachId);
277
- batch.update(batchRef, Object.assign({}, condition));
278
- }));
279
- yield batch.commit();
280
- res.send({ success: filterDataIds });
281
- }
282
- }
283
- catch (err) {
284
- res.status(400).json({ err: err });
285
- }
286
- });
287
- this.initUpdate = (req, res, workflow) => __awaiter(this, void 0, void 0, function* () {
288
- var _e;
289
- try {
290
- const valid = this.modelChecker(req.body.data) && req.body.id;
291
- if (valid) {
292
- const fbCollection = this.fbAdmin
293
- .firestore()
294
- .collection(this.collection);
295
- const dataQuery = yield fbCollection.doc(valid).get();
296
- if (!dataQuery.exists) {
297
- res.status(400).json({ err: "Invalid Security Configuration" });
298
- return;
299
- }
300
- const fbData = dataQuery.data();
301
- //INFO : Security Checker
302
- const validBaseConfig = (0, QueryModel_1.checkBaseConfig)(this.config, req);
303
- const validOpsConfig = (0, QueryModel_1.checkOpsConfig)(this.config, "update", req, fbData);
304
- if (!validBaseConfig || !validOpsConfig) {
305
- res.status(400).json({ err: "Invalid Security Configuration" });
306
- return;
307
- }
308
- if (req.body.unique && (fbData === null || fbData === void 0 ? void 0 : fbData[req.body.unique])) {
309
- const fields = req.body.unique === "id"
310
- ? req.body.id
311
- : (_e = req.body.data) === null || _e === void 0 ? void 0 : _e[req.body.unique];
312
- const fbSnapshot = yield fbCollection
313
- .where(req.body.unique, "==", fields)
314
- .get();
315
- if (!fbSnapshot.empty) {
316
- fbSnapshot.forEach((eachDataDoc) => {
317
- const eachData = eachDataDoc.data();
318
- if (req.body.id !== eachData.id) {
319
- res.status(400).json({
320
- err: `${fields !== null && fields !== void 0 ? fields : "Unique Fields Data"} exists`,
321
- });
322
- return;
323
- }
324
- });
325
- }
326
- }
327
- const { workflowUpdateFields, updatedFields } = (0, utils_1.compareUpdatedFields)(fbData, req.body.data);
328
- if (req.body.sensitive) {
329
- if ((0, moment_timezone_1.default)(req.body.data.baseUpdatedAt).isAfter((0, moment_timezone_1.default)(fbData.baseUpdatedAt.seconds * 1000))) {
330
- if (workflow)
331
- yield workflow(workflowUpdateFields);
332
- const data = this.parseModel(updatedFields);
333
- yield fbCollection.doc(valid).update(Object.assign({}, data));
334
- res.send({ success: true });
335
- }
336
- else {
337
- res.status(400).json({ err: "Refresh Sensitive Model" });
338
- }
339
- }
340
- else {
341
- if (workflow)
342
- yield workflow(workflowUpdateFields);
343
- const data = this.parseModel(updatedFields);
344
- yield fbCollection.doc(valid).update(Object.assign({}, data));
345
- res.send({ success: true });
346
- }
347
- }
348
- else {
349
- res.status(400).json({ err: "Invalid Model Structure" });
350
- }
351
- }
352
- catch (err) {
353
- res.status(400).json({ err: err });
354
- }
355
- });
356
- this.initBatchDelete = (req, res, workflow) => __awaiter(this, void 0, void 0, function* () {
357
- var _f, _g, _h, _j;
358
- try {
359
- if ((!Array.isArray(req.body.id) || ((_g = (_f = req.body.id) === null || _f === void 0 ? void 0 : _f.length) !== null && _g !== void 0 ? _g : 0) === 0) &&
360
- (!Array.isArray(req.body.query) || ((_j = (_h = req.body.query) === null || _h === void 0 ? void 0 : _h.length) !== null && _j !== void 0 ? _j : 0) === 0)) {
361
- throw "Invalid Batch Delete Config";
362
- }
363
- const batch = this.fbAdmin.firestore().batch();
364
- if (Array.isArray(req.body.id)) {
365
- const fbCollection = this.fbAdmin
366
- .firestore()
367
- .collection(this.collection)
368
- .where("id", "in", req.body.id);
369
- const fbSnapshot = yield fbCollection.get();
370
- const validBaseConfig = (0, QueryModel_1.checkBaseConfig)(this.config, req);
371
- //INFO : Security Checker
372
- let validOpsConfig = true;
373
- const dataList = [];
374
- if (fbSnapshot) {
375
- fbSnapshot.forEach((eachDataDoc) => {
376
- const eachData = eachDataDoc.data();
377
- dataList.push(eachData);
378
- if (!(0, QueryModel_1.checkOpsConfig)(this.config, "delete", req, eachData)) {
379
- validOpsConfig = false;
380
- }
381
- });
382
- }
383
- if (!validBaseConfig || !validOpsConfig) {
384
- res.status(400).json({ err: "Invalid Security Configuration" });
385
- return;
386
- }
387
- if (workflow)
388
- yield workflow(dataList);
389
- yield Promise.all(req.body.id.map((eachId) => __awaiter(this, void 0, void 0, function* () {
390
- const batchRef = yield this.fbAdmin
391
- .firestore()
392
- .collection(this.collection)
393
- .doc(eachId);
394
- batch.delete(batchRef);
395
- })));
396
- yield batch.commit();
397
- res.send({ success: req.body.id });
398
- }
399
- else {
400
- let fbCollection = this.fbAdmin.firestore().collection(this.collection);
401
- const queryList = req.body.query;
402
- const ids = [];
403
- if (queryList && queryList.length > 0) {
404
- queryList.map((eachQuery) => {
405
- var _a;
406
- const queryId = (_a = eachQuery.queryId) !== null && _a !== void 0 ? _a : "";
407
- const value = eachQuery.value;
408
- switch (eachQuery.type) {
409
- case "search":
410
- if (eachQuery.searchIds && eachQuery.searchIds.length > 0) {
411
- fbCollection = fbCollection
412
- .orderBy(eachQuery.searchIds[0])
413
- .startAt(value)
414
- .endAt(value + "\uf8ff");
415
- }
416
- break;
417
- case "=":
418
- fbCollection = fbCollection.where(queryId, "==", value);
419
- break;
420
- case "!=":
421
- fbCollection = fbCollection.where(queryId, "!=", value);
422
- break;
423
- case ">":
424
- fbCollection = fbCollection.where(queryId, ">", value);
425
- break;
426
- case "<":
427
- fbCollection = fbCollection.where(queryId, "<", value);
428
- break;
429
- case "><":
430
- if (Array.isArray(value) && value.length >= 2) {
431
- fbCollection = fbCollection
432
- .where(queryId, ">=", value[0])
433
- .where(queryId, "<=", value[1]);
434
- }
435
- break;
436
- case "in":
437
- fbCollection = fbCollection.where(queryId, "in", value);
438
- break;
439
- case "!in":
440
- fbCollection = fbCollection.where(queryId, "not-in", value);
441
- break;
442
- default:
443
- break;
444
- }
445
- });
446
- }
447
- const fbSnapshot = yield fbCollection.get();
448
- const validBaseConfig = (0, QueryModel_1.checkBaseConfig)(this.config, req);
449
- //INFO : Security Checker
450
- let validOpsConfig = true;
451
- const dataList = [];
452
- if (fbSnapshot) {
453
- fbSnapshot.forEach((eachDataDoc) => {
454
- const eachData = eachDataDoc.data();
455
- ids.push(eachData.id);
456
- dataList.push(eachData);
457
- if (!(0, QueryModel_1.checkOpsConfig)(this.config, "delete", req, eachData)) {
458
- validOpsConfig = false;
459
- }
460
- });
461
- }
462
- if (workflow)
463
- yield workflow(dataList);
464
- if (!validBaseConfig || !validOpsConfig) {
465
- res.status(400).json({ err: "Invalid Security Configuration" });
466
- return;
467
- }
468
- fbSnapshot.forEach((doc) => {
469
- batch.delete(doc.ref);
470
- });
471
- yield batch.commit();
472
- res.send({ success: ids });
473
- }
474
- }
475
- catch (err) {
476
- res.status(400).json({ err: err });
477
- }
478
- });
479
- this.initDelete = (req, res, workflow) => __awaiter(this, void 0, void 0, function* () {
480
- try {
481
- const valid = req.body.id;
482
- if (valid) {
483
- const dataQuery = yield this.fbAdmin
484
- .firestore()
485
- .collection(this.collection)
486
- .doc(valid)
487
- .get();
488
- if (!dataQuery.exists) {
489
- res.status(400).json({ err: "Invalid Security Configuration" });
490
- return;
491
- }
492
- const fbData = dataQuery.data();
493
- //INFO : Security Checker
494
- const validBaseConfig = (0, QueryModel_1.checkBaseConfig)(this.config, req);
495
- const validOpsConfig = (0, QueryModel_1.checkOpsConfig)(this.config, "delete", req, fbData);
496
- if (!validBaseConfig || !validOpsConfig) {
497
- res.status(400).json({ err: "Invalid Security Configuration" });
498
- return;
499
- }
500
- if (workflow)
501
- yield workflow(fbData);
502
- yield this.fbAdmin
503
- .firestore()
504
- .collection(this.collection)
505
- .doc(valid)
506
- .delete();
507
- res.send({ success: true });
508
- }
509
- else {
510
- res.status(400).json({ err: "Invalid Fields" });
511
- }
512
- }
513
- catch (err) {
514
- res.status(400).json({ err: err });
515
- }
516
- });
517
- this.initList = (req, res) => __awaiter(this, void 0, void 0, function* () {
518
- var _k, _l, _m, _o, _p;
519
- try {
520
- //INFO : Security Checker
521
- const validBaseConfig = (0, QueryModel_1.checkBaseConfig)(this.config, req);
522
- if (validBaseConfig) {
523
- const aggregate = req.body.aggregate;
524
- const queryList = (_k = req.body.query) !== null && _k !== void 0 ? _k : [];
525
- if (aggregate) {
526
- const queryId = (_l = aggregate.queryId) !== null && _l !== void 0 ? _l : "";
527
- const dateId = (_m = aggregate.dateId) !== null && _m !== void 0 ? _m : "baseUpdatedAt";
528
- const timezone = aggregate.timezone || "Asia/Kuala_lumpur";
529
- const dateRanges = (_o = aggregate.range) !== null && _o !== void 0 ? _o : [];
530
- const dataList = [];
531
- for (const dateRange of dateRanges) {
532
- //INFO : Step 1 - Query
533
- let fbCollection = this.fbAdmin
534
- .firestore()
535
- .collection(this.collection);
536
- if (queryList && queryList.length > 0) {
537
- queryList.map((eachQuery) => {
538
- var _a;
539
- const queryId = (_a = eachQuery.queryId) !== null && _a !== void 0 ? _a : "";
540
- const value = eachQuery.value;
541
- switch (eachQuery.type) {
542
- case "=":
543
- fbCollection = fbCollection.where(queryId, "==", value);
544
- break;
545
- case "!=":
546
- fbCollection = fbCollection.where(queryId, "!=", value);
547
- break;
548
- case ">":
549
- fbCollection = fbCollection.where(queryId, ">", value);
550
- break;
551
- case "<":
552
- fbCollection = fbCollection.where(queryId, "<", value);
553
- break;
554
- case "><":
555
- if (Array.isArray(value) && value.length >= 2) {
556
- fbCollection = fbCollection
557
- .where(queryId, ">=", value[0])
558
- .where(queryId, "<=", value[1]);
559
- }
560
- break;
561
- case "in":
562
- fbCollection = fbCollection.where(queryId, "in", value);
563
- break;
564
- case "!in":
565
- fbCollection = fbCollection.where(queryId, "not-in", value);
566
- break;
567
- default:
568
- break;
569
- }
570
- });
571
- }
572
- const date = dateRange.split("-");
573
- const [startDate, endDate = (0, moment_timezone_1.default)().tz(timezone).format("DD/MM/YYYY HH:mm:ss"),] = date;
574
- const isDuration = date.length === 2;
575
- const isValidStartDate = (0, moment_timezone_1.default)(startDate, "DD/MM/YYYY").isValid();
576
- const isValidEndDate = (0, moment_timezone_1.default)(endDate, "DD/MM/YYYY").isValid();
577
- const isoStartDate = (0, moment_timezone_1.default)(startDate, "DD/MM/YYYY HH:mm:ss")
578
- .tz(timezone)
579
- .format("YYYY-MM-DD HH:mm:ss");
580
- const isoEndDate = (0, moment_timezone_1.default)(endDate, "DD/MM/YYYY HH:mm:ss")
581
- .tz(timezone)
582
- .format("YYYY-MM-DD HH:mm:ss");
583
- if (!isValidStartDate || !isValidEndDate) {
584
- res
585
- .status(400)
586
- .json({ err: "Invalid Aggregate Range Configuration" });
587
- return;
588
- }
589
- const id = isDuration
590
- ? dateRange
591
- : `Begining until ${(0, moment_timezone_1.default)(isoStartDate).format("DD/MM/YYYY")}`;
592
- if (isDuration) {
593
- fbCollection = fbCollection
594
- .where(dateId, ">=", (0, moment_timezone_1.default)(isoStartDate).toDate())
595
- .where(dateId, "<=", (0, moment_timezone_1.default)(isoEndDate).toDate());
596
- }
597
- else {
598
- fbCollection = fbCollection.where(dateId, "<", (0, moment_timezone_1.default)(isoStartDate).toDate());
599
- }
600
- let value = 0;
601
- switch (aggregate.type) {
602
- case "count":
603
- const countFbSnapshot = yield fbCollection.count().get();
604
- value = countFbSnapshot.data().count;
605
- break;
606
- case "sum":
607
- const sumAggregateQuery = fbCollection.aggregate({
608
- sumValue: firestore_1.AggregateField.sum(queryId),
609
- });
610
- const sumFbSnapshot = yield sumAggregateQuery.get();
611
- value = sumFbSnapshot.data().sumValue;
612
- break;
613
- case "avg":
614
- const avgAggregateQuery = fbCollection.aggregate({
615
- avgValue: firestore_1.AggregateField.average(queryId),
616
- });
617
- const avgFbSnapshot = yield avgAggregateQuery.get();
618
- value = avgFbSnapshot.data().avgValue;
619
- break;
620
- case "value":
621
- fbCollection = fbCollection.limit(1);
622
- fbCollection = fbCollection.orderBy(dateId, "desc");
623
- const fbSnapshot = yield fbCollection.get();
624
- if (fbSnapshot) {
625
- fbSnapshot.forEach((eachDataDoc) => {
626
- const eachData = eachDataDoc.data();
627
- const clonedEachData = JSON.parse(JSON.stringify(eachData));
628
- value = clonedEachData[queryId];
629
- });
630
- }
631
- break;
632
- default:
633
- break;
634
- }
635
- dataList.push({
636
- _id: id,
637
- value: value,
638
- });
639
- }
640
- res.send({
641
- data: dataList,
642
- });
643
- }
644
- else {
645
- //INFO : Step 1 - Query
646
- let fbCollection = this.fbAdmin
647
- .firestore()
648
- .collection(this.collection);
649
- let searchQueryExists = "";
650
- if (queryList && queryList.length > 0) {
651
- queryList.map((eachQuery) => {
652
- var _a;
653
- const queryId = (_a = eachQuery.queryId) !== null && _a !== void 0 ? _a : "";
654
- const value = eachQuery.value;
655
- switch (eachQuery.type) {
656
- case "search":
657
- if (eachQuery.searchIds && eachQuery.searchIds.length > 0) {
658
- searchQueryExists = eachQuery.searchIds[0];
659
- fbCollection = fbCollection
660
- .orderBy(eachQuery.searchIds[0])
661
- .startAt(value)
662
- .endAt(value + "\uf8ff");
663
- }
664
- break;
665
- case "=":
666
- fbCollection = fbCollection.where(queryId, "==", value);
667
- break;
668
- case "!=":
669
- fbCollection = fbCollection.where(queryId, "!=", value);
670
- break;
671
- case ">":
672
- fbCollection = fbCollection.where(queryId, ">", value);
673
- break;
674
- case "<":
675
- fbCollection = fbCollection.where(queryId, "<", value);
676
- break;
677
- case "><":
678
- if (Array.isArray(value) && value.length >= 2) {
679
- fbCollection = fbCollection
680
- .where(queryId, ">=", value[0])
681
- .where(queryId, "<=", value[1]);
682
- }
683
- break;
684
- case "in":
685
- fbCollection = fbCollection.where(queryId, "in", value);
686
- break;
687
- case "!in":
688
- fbCollection = fbCollection.where(queryId, "not-in", value);
689
- break;
690
- default:
691
- break;
692
- }
693
- });
694
- }
695
- //INFO : Step 2 - Limit
696
- if (!req.body.stopLimit) {
697
- fbCollection = fbCollection.limit((_p = req.body.limit) !== null && _p !== void 0 ? _p : 10);
698
- }
699
- //INFO : Step 3 - Sort
700
- if (req.body.sort) {
701
- const sortReq = req.body.sort;
702
- if (searchQueryExists && sortReq.sortId !== searchQueryExists) {
703
- res
704
- .status(400)
705
- .json({ err: "Invalid Search Sort Configuration" });
706
- return;
707
- }
708
- if (!searchQueryExists) {
709
- fbCollection = fbCollection.orderBy(sortReq.sortId, sortReq.type === "asc" ? "asc" : "desc");
710
- }
711
- }
712
- //INFO : Step 4 - Pagination
713
- if (req.body.cursor) {
714
- fbCollection = fbCollection.startAfter(req.body.cursor);
715
- }
716
- const fbSnapshot = yield fbCollection.get();
717
- //INFO : Security Checker
718
- let validOpsConfig = true;
719
- const dataList = [];
720
- if (fbSnapshot) {
721
- fbSnapshot.forEach((eachDataDoc) => {
722
- const eachData = eachDataDoc.data();
723
- dataList.push(eachData);
724
- if (!(0, QueryModel_1.checkOpsConfig)(this.config, "read", req, eachData)) {
725
- validOpsConfig = false;
726
- }
727
- });
728
- }
729
- if (!validBaseConfig || !validOpsConfig) {
730
- res.status(400).json({ err: "Invalid Security Configuration" });
731
- return;
732
- }
733
- let cursor = "";
734
- if (dataList.length === req.body.limit) {
735
- let sortCol = "id";
736
- if (req.body.sort) {
737
- const sortReq = req.body.sort;
738
- sortCol = sortReq.sortId;
739
- }
740
- cursor = dataList[req.body.limit - 1][sortCol];
741
- }
742
- res.send({
743
- data: dataList,
744
- count: cursor,
745
- });
746
- }
747
- }
748
- else {
749
- res.status(400).json({ err: "Invalid Security Configuration" });
750
- }
751
- }
752
- catch (err) {
753
- if (err.message)
754
- res.status(400).json({ err: err.message });
755
- else
756
- res.status(400).json({ err: err });
757
- }
758
- });
759
- this.init = () => {
760
- const router = this.lib.express.Router();
761
- /**
762
- * @Input :
763
- * data - Model
764
- * unique - string (Optional)
765
- */
766
- router.post("/create", (req, res) => {
767
- this.initCreate(req, res);
768
- });
769
- /**
770
- * @Input :
771
- * data - Model
772
- * unique - string (Optional)
773
- */
774
- router.post("/batchCreate", (req, res) => {
775
- this.initBatchCreate(req, res);
776
- });
777
- /**
778
- * @Input :
779
- * id - string
780
- */
781
- router.post("/get", (req, res) => {
782
- this.initGet(req, res);
783
- });
784
- /**
785
- * @Input :
786
- * data - Model
787
- * id - string
788
- * unique - string (Optional)
789
- */
790
- router.post("/update", (req, res) => {
791
- this.initUpdate(req, res);
792
- });
793
- /**
794
- * @Input :
795
- * data - Model
796
- * query - Query[]
797
- * unsetData - string[] (Unset Attribute Id) (Optional)
798
- * isOr - boolean (Optional)
799
- */
800
- router.post("/batchUpdate", (req, res) => {
801
- this.initBatchUpdate(req, res);
802
- });
803
- /**
804
- * @Input :
805
- * id - string
806
- */
807
- router.post("/delete", (req, res) => {
808
- this.initDelete(req, res);
809
- });
810
- /**
811
- * @Input :
812
- * id - string[]
813
- */
814
- router.post("/batchDelete", (req, res) => {
815
- this.initBatchDelete(req, res);
816
- });
817
- /**
818
- * @Input
819
- * query - Query interface (Optional)
820
- * cursor - any (Optional)
821
- * limit - number (Optional)
822
- * sort - Sort interface (Optional)
823
- * stopLimit - boolean to retreive all data (Optional)
824
- *
825
- */
826
- router.post("/list", (req, res) => {
827
- this.initList(req, res);
828
- });
829
- return router;
830
- };
831
- this.fbAdmin = fbAdmin;
832
- this.collection = collection;
833
- this.isProd = isProd;
834
- this.config = config;
835
- this.modelChecker = modelChecker;
836
- this.lib = lib;
837
- }
838
- }
839
- exports.FirebaseWrapper = FirebaseWrapper;
1
+ var __awaiter=this&&this.__awaiter||function(e,o,d,n){return new(d=d||Promise)(function(i,t){function s(e){try{r(n.next(e))}catch(e){t(e)}}function a(e){try{r(n.throw(e))}catch(e){t(e)}}function r(e){var t;e.done?i(e.value):((t=e.value)instanceof d?t:new d(function(e){e(t)})).then(s,a)}r((n=n.apply(e,o||[])).next())})},__importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.FirebaseWrapper=void 0;let firestore_1=require("firebase-admin/firestore"),dayjs_1=__importDefault(require("./dayjs")),QueryModel_1=require("../model/QueryModel"),utils_1=require("./utils");class FirebaseWrapper{constructor(e,t,i,s,a,r){this.fbAdmin="",this.collection="",this.isProd=!1,this.config={baseConfig:[],opsConfig:{read:[],create:[],update:[],delete:[]}},this.modelChecker=e=>!1,this.parseModel=e=>(delete e.id,e.baseUpdatedAt=(0,dayjs_1.default)().toDate(),e),this.initBatchCreate=(n,l,c)=>__awaiter(this,void 0,void 0,function*(){try{let a=this.fbAdmin.firestore().batch(),r=this.fbAdmin.firestore().collection(this.collection);if(Array.isArray(n.body.data)){let t=!0;if(n.body.data.map(e=>{this.modelChecker(e)||(t=!1)}),t){var e=n.body.data,o=(0,QueryModel_1.checkBaseConfig)(this.config,n);let t=!0,i=[],s=[];if(e.map(e=>{i.push(e.id),(0,QueryModel_1.checkOpsConfig)(this.config,"update",n,e)||(t=!1),n.body.unique&&null!=e&&e[n.body.unique]&&s.push(null==e?void 0:e[n.body.unique])}),o&&t){if(0<s.length){var d=yield r.find(n.body.unique,"in",s).get();let t=[];if(d.empty||d.forEach(e=>{e=e.data();t.push(e)}),0<t.length)return void l.status(400).json({err:`Unique:${t.map(e=>null==e?void 0:e[n.body.unique])} exists`})}c&&(yield c(e)),yield Promise.all(e.map(t=>__awaiter(this,void 0,void 0,function*(){t.baseUpdatedAt=(0,dayjs_1.default)().toDate();var e=r.doc(t.id);a.set(e,Object.assign({},t))}))),yield a.commit(),l.send({success:i})}else l.status(400).json({err:"Invalid Security Configuration"})}else l.status(400).json({err:"Invalid Model Structure"})}else l.status(400).json({err:"Invalid Fields"})}catch(e){l.status(400).json({err:e})}}),this.initCreate=(r,o,d)=>__awaiter(this,void 0,void 0,function*(){var e,t;try{if(this.modelChecker(r.body.data)){var i=(0,QueryModel_1.checkBaseConfig)(this.config,r),s=(0,QueryModel_1.checkOpsConfig)(this.config,"create",r,r.body.data);if(i&&s){var a=this.fbAdmin.firestore().collection(this.collection);if(r.body.data.baseUpdatedAt=(0,dayjs_1.default)().toDate(),r.body.unique&&null!=(e=r.body.data)&&e[r.body.unique])if(!(yield a.where(r.body.unique,"==",null==(t=r.body.data)?void 0:t[r.body.unique]).get()).empty)return void o.status(400).json({err:`Unique:${r.body.data[r.body.unique]} exists`});d&&(yield d(r.body.data)),yield a.doc(r.body.data.id).set(r.body.data),o.send({success:!0})}else o.status(400).json({err:"Invalid Security Configuration"})}else o.status(400).json({err:"Invalid Model Structure"})}catch(e){o.status(400).json({err:e})}}),this.initGet=(r,o)=>__awaiter(this,void 0,void 0,function*(){try{var e,t,i,s,a=r.body.id;a?(e=yield this.fbAdmin.firestore().collection(this.collection).doc(a).get()).exists&&(t=e.data(),i=(0,QueryModel_1.checkBaseConfig)(this.config,r),s=(0,QueryModel_1.checkOpsConfig)(this.config,"read",r,t),i)&&s?o.send({data:t}):o.status(400).json({err:"Invalid Security Configuration"}):o.status(400).json({err:"Invalid Fields"})}catch(e){o.status(400).json({err:e})}}),this.initBatchUpdate=(b,g,v)=>__awaiter(this,void 0,void 0,function*(){let e,t,o=this.fbAdmin.firestore().batch();try{var i=this.modelChecker(b.body.data)&&b.body.query,d=this.parseModel(null!=(e=b.body.data)?e:[]),n=null!=(t=b.body.query)?t:[],l=b.body.isOr||!1,c=b.body.unsetData;if(i){var u=this.fbAdmin.firestore().collection(this.collection);let a=[];n.forEach(e=>{var t,i=null!=(t=e.queryId)?t:"",s=e.value;switch(e.type){case"=":a.push(this.fbAdmin.firestore.Filter.where(i,"==",s));break;case"!=":a.push(this.fbAdmin.firestore.Filter.where(i,"!=",s));break;case">":a.push(this.fbAdmin.firestore.Filter.where(i,">",s));break;case"<":a.push(this.fbAdmin.firestore.Filter.where(i,"<",s));break;case"><":Array.isArray(s)&&2<=s.length&&a.push(this.fbAdmin.firestore.Filter.where(i,">=",s[0]),this.fbAdmin.firestore.Filter.where(i,"<=",s[1]));break;case"in":a.push(this.fbAdmin.firestore.Filter.where(i,"in",s))}});var h=l?this.fbAdmin.firestore.Filter.or(...a):this.fbAdmin.firestore.Filter.and(...a),y=yield u.where(h).get(),f=(0,QueryModel_1.checkBaseConfig)(this.config,b);let i=!0,s=[],r=[];if(y&&y.forEach(e=>{var t=e.data(),t=(r.push(t.id),!b.body.sensitive||(0,dayjs_1.default)(b.body.data.baseUpdatedAt).isAfter((0,dayjs_1.default)(1e3*t.baseUpdatedAt.seconds))||g.status(400).json({err:"Refresh Sensitive Model"}),(0,QueryModel_1.checkOpsConfig)(this.config,"update",b,t)||(i=!1),(0,utils_1.compareUpdatedFields)(e,b.body.data)).workflowUpdateFields;s.push(t)}),f&&i){let t={};c&&c.forEach(e=>{t[e]=this.fbAdmin.firestore.FieldValue.delete()}),d&&(t=Object.assign(Object.assign({},d),t)),v&&(yield v(s)),yield Promise.all(r.map(e=>{e=this.fbAdmin.firestore().collection(this.collection).doc(e);o.update(e,Object.assign({},t))})),yield o.commit(),g.send({success:r})}else g.status(400).json({err:"Invalid Security Configuration"})}}catch(e){g.status(400).json({err:e})}}),this.initUpdate=(h,y,f)=>__awaiter(this,void 0,void 0,function*(){var e;try{var t=this.modelChecker(h.body.data)&&h.body.id;if(t){var i=this.fbAdmin.firestore().collection(this.collection),s=yield i.doc(t).get();if(s.exists){var a=s.data(),r=(0,QueryModel_1.checkBaseConfig)(this.config,h),o=(0,QueryModel_1.checkOpsConfig)(this.config,"update",h,a);if(r&&o){if(h.body.unique&&null!=a&&a[h.body.unique]){let t="id"===h.body.unique?h.body.id:null==(e=h.body.data)?void 0:e[h.body.unique];var d=yield i.where(h.body.unique,"==",t).get();d.empty||d.forEach(e=>{e=e.data();h.body.id!==e.id&&y.status(400).json({err:`${null!=t?t:"Unique Fields Data"} exists`})})}var n,l,{workflowUpdateFields:c,updatedFields:u}=(0,utils_1.compareUpdatedFields)(a,h.body.data);h.body.sensitive?(0,dayjs_1.default)(h.body.data.baseUpdatedAt).isAfter((0,dayjs_1.default)(1e3*a.baseUpdatedAt.seconds))?(f&&(yield f(c)),n=this.parseModel(u),yield i.doc(t).update(Object.assign({},n)),y.send({success:!0})):y.status(400).json({err:"Refresh Sensitive Model"}):(f&&(yield f(c)),l=this.parseModel(u),yield i.doc(t).update(Object.assign({},l)),y.send({success:!0}))}else y.status(400).json({err:"Invalid Security Configuration"})}else y.status(400).json({err:"Invalid Security Configuration"})}else y.status(400).json({err:"Invalid Model Structure"})}catch(e){y.status(400).json({err:e})}}),this.initBatchDelete=(c,u,h)=>__awaiter(this,void 0,void 0,function*(){var e,t,i,s;try{if(!(Array.isArray(c.body.id)&&0!==(null!=(t=null==(e=c.body.id)?void 0:e.length)?t:0)||Array.isArray(c.body.query)&&0!==(null!=(s=null==(i=c.body.query)?void 0:i.length)?s:0)))throw"Invalid Batch Delete Config";let r=this.fbAdmin.firestore().batch();if(Array.isArray(c.body.id)){var a=yield this.fbAdmin.firestore().collection(this.collection).where("id","in",c.body.id).get(),o=(0,QueryModel_1.checkBaseConfig)(this.config,c);let t=!0,i=[];a&&a.forEach(e=>{e=e.data();i.push(e),(0,QueryModel_1.checkOpsConfig)(this.config,"delete",c,e)||(t=!1)}),o&&t?(h&&(yield h(i)),yield Promise.all(c.body.id.map(t=>__awaiter(this,void 0,void 0,function*(){var e=yield this.fbAdmin.firestore().collection(this.collection).doc(t);r.delete(e)}))),yield r.commit(),u.send({success:c.body.id})):u.status(400).json({err:"Invalid Security Configuration"})}else{let a=this.fbAdmin.firestore().collection(this.collection);var d=c.body.query;let t=[];d&&0<d.length&&d.map(e=>{var t,i=null!=(t=e.queryId)?t:"",s=e.value;switch(e.type){case"search":e.searchIds&&0<e.searchIds.length&&(a=a.orderBy(e.searchIds[0]).startAt(s).endAt(s+""));break;case"=":a=a.where(i,"==",s);break;case"!=":a=a.where(i,"!=",s);break;case">":a=a.where(i,">",s);break;case"<":a=a.where(i,"<",s);break;case"><":Array.isArray(s)&&2<=s.length&&(a=a.where(i,">=",s[0]).where(i,"<=",s[1]));break;case"in":a=a.where(i,"in",s);break;case"!in":a=a.where(i,"not-in",s)}});var n=yield a.get(),l=(0,QueryModel_1.checkBaseConfig)(this.config,c);let i=!0,s=[];n&&n.forEach(e=>{e=e.data();t.push(e.id),s.push(e),(0,QueryModel_1.checkOpsConfig)(this.config,"delete",c,e)||(i=!1)}),h&&(yield h(s)),l&&i?(n.forEach(e=>{r.delete(e.ref)}),yield r.commit(),u.send({success:t})):u.status(400).json({err:"Invalid Security Configuration"})}}catch(e){u.status(400).json({err:e})}}),this.initDelete=(r,o,d)=>__awaiter(this,void 0,void 0,function*(){try{var e,t,i,s,a=r.body.id;a?(e=yield this.fbAdmin.firestore().collection(this.collection).doc(a).get()).exists&&(t=e.data(),i=(0,QueryModel_1.checkBaseConfig)(this.config,r),s=(0,QueryModel_1.checkOpsConfig)(this.config,"delete",r,t),i)&&s?(d&&(yield d(t)),yield this.fbAdmin.firestore().collection(this.collection).doc(a).delete(),o.send({success:!0})):o.status(400).json({err:"Invalid Security Configuration"}):o.status(400).json({err:"Invalid Fields"})}catch(e){o.status(400).json({err:e})}}),this.initList=(Y,F)=>__awaiter(this,void 0,void 0,function*(){var e,t,s,a,o;try{var d=(0,QueryModel_1.checkBaseConfig)(this.config,Y);if(d){var r=Y.body.aggregate,n=null!=(e=Y.body.query)?e:[];if(r){let i=null!=(t=r.queryId)?t:"";var l,c=null!=(s=r.dateId)?s:"baseUpdatedAt",u=r.timezone||"Asia/Kuala_lumpur",h=null!=(a=r.range)?a:[],y=[];for(l of h){let a=this.fbAdmin.firestore().collection(this.collection);n&&0<n.length&&n.map(e=>{var t,i=null!=(t=e.queryId)?t:"",s=e.value;switch(e.type){case"=":a=a.where(i,"==",s);break;case"!=":a=a.where(i,"!=",s);break;case">":a=a.where(i,">",s);break;case"<":a=a.where(i,"<",s);break;case"><":Array.isArray(s)&&2<=s.length&&(a=a.where(i,">=",s[0]).where(i,"<=",s[1]));break;case"in":a=a.where(i,"in",s);break;case"!in":a=a.where(i,"not-in",s)}});var f=l.split("-"),[b,g=(0,dayjs_1.default)().tz(u).format("DD/MM/YYYY HH:mm:ss")]=f,v=2===f.length,p=(0,dayjs_1.default)(b,"DD/MM/YYYY").isValid(),m=(0,dayjs_1.default)(g,"DD/MM/YYYY").isValid(),_=(0,dayjs_1.default)(b,"DD/MM/YYYY HH:mm:ss").tz(u).format("YYYY-MM-DD HH:mm:ss"),w=(0,dayjs_1.default)(g,"DD/MM/YYYY HH:mm:ss").tz(u).format("YYYY-MM-DD HH:mm:ss");if(!p||!m)return void F.status(400).json({err:"Invalid Aggregate Range Configuration"});var A=v?l:"Begining until "+(0,dayjs_1.default)(_).format("DD/MM/YYYY");a=v?a.where(c,">=",(0,dayjs_1.default)(_).toDate()).where(c,"<=",(0,dayjs_1.default)(w).toDate()):a.where(c,"<",(0,dayjs_1.default)(_).toDate());let t=0;switch(r.type){case"count":var j=yield a.count().get();t=j.data().count;break;case"sum":var k=yield a.aggregate({sumValue:firestore_1.AggregateField.sum(i)}).get();t=k.data().sumValue;break;case"avg":var M=yield a.aggregate({avgValue:firestore_1.AggregateField.average(i)}).get();t=M.data().avgValue;break;case"value":var C=yield(a=(a=a.limit(1)).orderBy(c,"desc")).get();C&&C.forEach(e=>{e=e.data(),e=JSON.parse(JSON.stringify(e));t=e[i]})}y.push({_id:A,value:t})}F.send({data:y})}else{let a=this.fbAdmin.firestore().collection(this.collection),r="";if(n&&0<n.length&&n.map(e=>{var t,i=null!=(t=e.queryId)?t:"",s=e.value;switch(e.type){case"search":e.searchIds&&0<e.searchIds.length&&(r=e.searchIds[0],a=a.orderBy(e.searchIds[0]).startAt(s).endAt(s+""));break;case"=":a=a.where(i,"==",s);break;case"!=":a=a.where(i,"!=",s);break;case">":a=a.where(i,">",s);break;case"<":a=a.where(i,"<",s);break;case"><":Array.isArray(s)&&2<=s.length&&(a=a.where(i,">=",s[0]).where(i,"<=",s[1]));break;case"in":a=a.where(i,"in",s);break;case"!in":a=a.where(i,"not-in",s)}}),Y.body.stopLimit||(a=a.limit(null!=(o=Y.body.limit)?o:10)),Y.body.sort){var I=Y.body.sort;if(r&&I.sortId!==r)return void F.status(400).json({err:"Invalid Search Sort Configuration"});r||(a=a.orderBy(I.sortId,"asc"===I.type?"asc":"desc"))}var q,D=yield(a=Y.body.cursor?a.startAfter(Y.body.cursor):a).get();let t=!0,i=[];if(D&&D.forEach(e=>{e=e.data();i.push(e),(0,QueryModel_1.checkOpsConfig)(this.config,"read",Y,e)||(t=!1)}),d&&t){let t="";if(i.length===Y.body.limit){let e="id";Y.body.sort&&(q=Y.body.sort,e=q.sortId),t=i[Y.body.limit-1][e]}F.send({data:i,count:t})}else F.status(400).json({err:"Invalid Security Configuration"})}}else F.status(400).json({err:"Invalid Security Configuration"})}catch(e){e.message?F.status(400).json({err:e.message}):F.status(400).json({err:e})}}),this.init=()=>{var e=this.lib.express.Router();return e.post("/create",(e,t)=>{this.initCreate(e,t)}),e.post("/batchCreate",(e,t)=>{this.initBatchCreate(e,t)}),e.post("/get",(e,t)=>{this.initGet(e,t)}),e.post("/update",(e,t)=>{this.initUpdate(e,t)}),e.post("/batchUpdate",(e,t)=>{this.initBatchUpdate(e,t)}),e.post("/delete",(e,t)=>{this.initDelete(e,t)}),e.post("/batchDelete",(e,t)=>{this.initBatchDelete(e,t)}),e.post("/list",(e,t)=>{this.initList(e,t)}),e},this.fbAdmin=e,this.collection=t,this.isProd=i,this.config=s,this.modelChecker=a,this.lib=r}}exports.FirebaseWrapper=FirebaseWrapper;