drapcode-utility 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 (39) hide show
  1. package/build/encryption/index.d.ts +15 -0
  2. package/build/encryption/index.js +255 -0
  3. package/build/errors/app-error.d.ts +6 -0
  4. package/build/errors/app-error.js +30 -0
  5. package/build/errors/axios-error.d.ts +13 -0
  6. package/build/errors/axios-error.js +78 -0
  7. package/build/errors/bad-request-error.d.ts +9 -0
  8. package/build/errors/bad-request-error.js +32 -0
  9. package/build/errors/custom-error.d.ts +8 -0
  10. package/build/errors/custom-error.js +26 -0
  11. package/build/errors/not-found.d.ts +8 -0
  12. package/build/errors/not-found.js +31 -0
  13. package/build/index.d.ts +17 -0
  14. package/build/index.js +29 -0
  15. package/build/middlewares/api-limiter.d.ts +1 -0
  16. package/build/middlewares/api-limiter.js +21 -0
  17. package/build/middlewares/error-logger.d.ts +3 -0
  18. package/build/middlewares/error-logger.js +74 -0
  19. package/build/middlewares/interceptor-logger-new.d.ts +2 -0
  20. package/build/middlewares/interceptor-logger-new.js +54 -0
  21. package/build/middlewares/interceptor-logger.d.ts +2 -0
  22. package/build/middlewares/interceptor-logger.js +42 -0
  23. package/build/middlewares/redis/request-log.d.ts +1 -0
  24. package/build/middlewares/redis/request-log.js +79 -0
  25. package/build/utils/check-error.d.ts +9 -0
  26. package/build/utils/check-error.js +188 -0
  27. package/build/utils/date-util.d.ts +8 -0
  28. package/build/utils/date-util.js +104 -0
  29. package/build/utils/prepare-query.d.ts +132 -0
  30. package/build/utils/prepare-query.js +94 -0
  31. package/build/utils/query-parser.d.ts +11 -0
  32. package/build/utils/query-parser.js +778 -0
  33. package/build/utils/query-paser-new.d.ts +1 -0
  34. package/build/utils/query-paser-new.js +682 -0
  35. package/build/utils/util.d.ts +27 -0
  36. package/build/utils/util.js +373 -0
  37. package/build/utils/uuid-generator.d.ts +1 -0
  38. package/build/utils/uuid-generator.js +65 -0
  39. package/package.json +47 -0
@@ -0,0 +1,778 @@
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 __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (_) try {
18
+ 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;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ var __spreadArrays = (this && this.__spreadArrays) || function () {
39
+ for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
40
+ for (var r = Array(s), k = 0, i = 0; i < il; i++)
41
+ for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
42
+ r[k] = a[j];
43
+ return r;
44
+ };
45
+ var __importDefault = (this && this.__importDefault) || function (mod) {
46
+ return (mod && mod.__esModule) ? mod : { "default": mod };
47
+ };
48
+ Object.defineProperty(exports, "__esModule", { value: true });
49
+ exports.getMinMaxValue = exports.isEntityInCondition = exports.queryParser = void 0;
50
+ var moment_1 = __importDefault(require("moment"));
51
+ var drapcode_constant_1 = require("drapcode-constant");
52
+ var date_util_1 = require("./date-util");
53
+ var util_1 = require("./util");
54
+ var queryParser = function (collectionName, query, constants, externalParams, currentUser, timezone, searchObj, refCollectionFieldsInItems, searchQueryTypeObj, currentTenant) {
55
+ if (currentUser === void 0) { currentUser = {}; }
56
+ if (searchObj === void 0) { searchObj = null; }
57
+ if (refCollectionFieldsInItems === void 0) { refCollectionFieldsInItems = null; }
58
+ if (searchQueryTypeObj === void 0) { searchQueryTypeObj = {}; }
59
+ if (currentTenant === void 0) { currentTenant = {}; }
60
+ return __awaiter(void 0, void 0, void 0, function () {
61
+ var filterQuery, aggregateQuery, queryStr, searchQueryObj, _a, searchAggregateQuery, likeQuery, finalQuery, _b, searchAggregateQuery, likeQuery, projection, finder, sortBy, orderBy, offset, limit, direction, str;
62
+ var _c, _d;
63
+ return __generator(this, function (_e) {
64
+ switch (_e.label) {
65
+ case 0:
66
+ if (!collectionName)
67
+ return [2 /*return*/, ""];
68
+ if (!query)
69
+ return [2 /*return*/, ""];
70
+ console.log("***1*** queryParser ***");
71
+ filterQuery = mongoFilterQuery(query, externalParams, constants, currentUser, currentTenant);
72
+ console.log("**************************");
73
+ console.log("filterQuery", JSON.stringify(filterQuery));
74
+ console.log("==> searchQueryTypeObj :>>", searchQueryTypeObj);
75
+ aggregateQuery = [];
76
+ queryStr = ".aggregate([])";
77
+ if (filterQuery.length &&
78
+ ((filterQuery[0].$or && filterQuery[0].$or.length) ||
79
+ (filterQuery[0].$and && filterQuery[0].$and.length))) {
80
+ searchQueryObj = null;
81
+ if (searchObj) {
82
+ _a = getSearchObjQuery(searchObj, searchQueryTypeObj, timezone), searchAggregateQuery = _a.searchAggregateQuery, likeQuery = _a.likeQuery;
83
+ aggregateQuery = __spreadArrays(aggregateQuery, searchAggregateQuery);
84
+ if (likeQuery && likeQuery.length > 0) {
85
+ searchQueryObj = likeQuery;
86
+ }
87
+ }
88
+ finalQuery = { $and: filterQuery };
89
+ if (searchQueryObj) {
90
+ (_c = finalQuery.$and).push.apply(_c, searchQueryObj);
91
+ }
92
+ aggregateQuery.push({ $match: finalQuery });
93
+ }
94
+ else if (searchObj) {
95
+ _b = getSearchObjQuery(searchObj, searchQueryTypeObj, timezone), searchAggregateQuery = _b.searchAggregateQuery, likeQuery = _b.likeQuery;
96
+ aggregateQuery = __spreadArrays(aggregateQuery, searchAggregateQuery);
97
+ if (likeQuery.length) {
98
+ // aggregateQuery.push({ $match: { $or: likeQuery } });
99
+ aggregateQuery.push({ $match: { $and: likeQuery } });
100
+ }
101
+ }
102
+ console.log("==> query", query);
103
+ projection = mongoSelectQuery(query);
104
+ finder = query.finder, sortBy = query.sortBy, orderBy = query.orderBy;
105
+ if (!(finder != "COUNT" && refCollectionFieldsInItems)) return [3 /*break*/, 2];
106
+ return [4 /*yield*/, Promise.all(refCollectionFieldsInItems.map(function (field) {
107
+ var _a, _b, _c;
108
+ if (["reference", "multi_reference", "belongsTo"].includes(field.type)) {
109
+ var collectionName_1 = field.refCollection
110
+ ? field.refCollection["collectionName"]
111
+ : null;
112
+ if (collectionName_1) {
113
+ if (field.type === "belongsTo") {
114
+ aggregateQuery.push({
115
+ $lookup: {
116
+ from: "" + collectionName_1,
117
+ localField: field.fieldName,
118
+ foreignField: "uuid",
119
+ as: field.fieldName,
120
+ },
121
+ });
122
+ aggregateQuery.push({
123
+ $addFields: (_a = {},
124
+ _a["_$belongsToMetaData"] = field,
125
+ _a),
126
+ });
127
+ }
128
+ else {
129
+ aggregateQuery.push({
130
+ $lookup: {
131
+ from: "" + collectionName_1,
132
+ let: (_b = {}, _b["" + field.fieldName] = "$" + field.fieldName, _b),
133
+ pipeline: [
134
+ {
135
+ $match: {
136
+ $expr: {
137
+ $in: [
138
+ "$uuid",
139
+ {
140
+ $cond: {
141
+ if: {
142
+ $in: ["$$" + field.fieldName, ["", null]],
143
+ },
144
+ then: [],
145
+ else: { $ifNull: ["$$" + field.fieldName, []] },
146
+ },
147
+ },
148
+ ],
149
+ },
150
+ },
151
+ },
152
+ {
153
+ $lookup: {
154
+ from: "user",
155
+ let: { createdBy: "$createdBy" },
156
+ pipeline: [
157
+ {
158
+ $match: {
159
+ $expr: { $eq: ["$uuid", "$$createdBy"] },
160
+ },
161
+ },
162
+ { $project: { _id: 0, password: 0 } },
163
+ ],
164
+ as: "createdBy",
165
+ },
166
+ },
167
+ ],
168
+ as: field.fieldName,
169
+ },
170
+ });
171
+ }
172
+ }
173
+ }
174
+ if (field.type === "createdBy")
175
+ aggregateQuery.push({
176
+ $lookup: {
177
+ from: "user",
178
+ let: (_c = {}, _c["" + field.fieldName] = "$" + field.fieldName, _c),
179
+ pipeline: [
180
+ {
181
+ $match: { $expr: { $eq: ["$uuid", "$$" + field.fieldName] } },
182
+ },
183
+ { $project: { _id: 0, password: 0 } },
184
+ ],
185
+ as: field.fieldName,
186
+ },
187
+ });
188
+ }))];
189
+ case 1:
190
+ _e.sent();
191
+ _e.label = 2;
192
+ case 2:
193
+ if (finder != "COUNT" && !util_1.isEmpty(projection)) {
194
+ aggregateQuery.push({ $project: projection });
195
+ }
196
+ if (finder === "COUNT") {
197
+ aggregateQuery.push({ $group: { _id: null, count: { $sum: 1 } } });
198
+ }
199
+ offset = externalParams.offset || 0;
200
+ limit = externalParams.limit || 20000;
201
+ if (externalParams.pagination == "false") {
202
+ limit = 0;
203
+ sortBy = 0;
204
+ }
205
+ if (finder != "COUNT" && sortBy) {
206
+ direction = orderBy && orderBy == "asc" ? 1 : -1;
207
+ aggregateQuery.push({ $sort: (_d = {}, _d[sortBy] = direction, _d._id = 1, _d) });
208
+ }
209
+ if (finder != "COUNT" && limit) {
210
+ aggregateQuery.push({ $skip: +offset }, { $limit: +limit });
211
+ }
212
+ console.log("==> aggregateQuery", aggregateQuery);
213
+ queryStr = ".aggregate(" + JSON.stringify(aggregateQuery) + ", { collation: { locale: \"en\" } })";
214
+ str = "req.db.collection('" + collectionName + "')" + queryStr;
215
+ str += ".toArray()";
216
+ return [2 /*return*/, str];
217
+ }
218
+ });
219
+ });
220
+ };
221
+ exports.queryParser = queryParser;
222
+ var toBoolean = function (value) {
223
+ if (!value) {
224
+ return false;
225
+ }
226
+ switch (value.toLocaleLowerCase()) {
227
+ case "true":
228
+ case "1":
229
+ case "on":
230
+ case "yes":
231
+ return true;
232
+ default:
233
+ return false;
234
+ }
235
+ };
236
+ var mongoFilterQuery = function (query, externalParams, constants, currentUser, currentTenant) {
237
+ if (currentUser === void 0) { currentUser = {}; }
238
+ if (currentTenant === void 0) { currentTenant = {}; }
239
+ var filterQuery = { $or0: [] };
240
+ var conditions = query.conditions;
241
+ var queryConjunctions = [];
242
+ conditions.forEach(function (queryObj, index) {
243
+ var query = queryObj.query, requiredExternal = queryObj.requiredExternal;
244
+ console.log("query :>> ", JSON.stringify(query));
245
+ var mongoQuery = queryToMongo(query, requiredExternal, externalParams, constants, currentUser, currentTenant);
246
+ console.log(":::::::::mongoQuery::::", JSON.stringify(mongoQuery));
247
+ queryConjunctions.push(queryObj.conjunctionType);
248
+ if (queryObj.conjunctionType == "OR") {
249
+ var lastKey = Object.keys(filterQuery)[Object.keys(filterQuery).length - 1];
250
+ if (filterQuery[lastKey] && Array.isArray(filterQuery[lastKey])) {
251
+ filterQuery[lastKey].push(mongoQuery);
252
+ }
253
+ else {
254
+ filterQuery["$or" + index] = [mongoQuery];
255
+ }
256
+ }
257
+ else if (queryObj.conjunctionType == "AND") {
258
+ var lastKey = Object.keys(filterQuery)[Object.keys(filterQuery).length - 1];
259
+ if (filterQuery[lastKey] && Array.isArray(filterQuery[lastKey])) {
260
+ filterQuery[lastKey].push(mongoQuery);
261
+ }
262
+ else {
263
+ filterQuery["$and" + index] = [mongoQuery];
264
+ }
265
+ }
266
+ else {
267
+ filterQuery["$or" + index] = [mongoQuery];
268
+ }
269
+ });
270
+ console.log("==> *** filterQuery mongoFilterQuery :>> ", filterQuery);
271
+ var hasAndQueryConjunction = queryConjunctions.includes("AND");
272
+ var resultQuery = modifyQuery(filterQuery, hasAndQueryConjunction);
273
+ console.log("=>> resultQuery :>> ", resultQuery);
274
+ console.log("=>> JSON.stringify(resultQuery) :>> ", JSON.stringify(resultQuery));
275
+ return resultQuery;
276
+ };
277
+ var mongoSelectQuery = function (query) {
278
+ if (query === void 0) { query = {}; }
279
+ var projection = {};
280
+ var fieldsInclude = query.fieldsInclude, fieldsExclude = query.fieldsExclude;
281
+ if (!fieldsExclude)
282
+ fieldsExclude = [];
283
+ if (fieldsInclude[0] === "*") {
284
+ fieldsExclude.map(function (field) {
285
+ if (field)
286
+ return (projection["" + field] = 0);
287
+ });
288
+ }
289
+ else {
290
+ fieldsInclude.map(function (field) {
291
+ if (field)
292
+ return (projection["" + field] = 1);
293
+ });
294
+ }
295
+ return projection;
296
+ };
297
+ var modifyQuery = function (obj, hasAndQueryConjunction) {
298
+ if (obj === void 0) { obj = {}; }
299
+ if (hasAndQueryConjunction === void 0) { hasAndQueryConjunction = false; }
300
+ var arr = [];
301
+ console.log("🚀 ~ file: query-parser.ts:294 ~ modifyQuery ~ hasAndQueryConjunction:", hasAndQueryConjunction);
302
+ Object.entries(obj).forEach(function (_a) {
303
+ var key = _a[0], value = _a[1];
304
+ if (hasAndQueryConjunction) {
305
+ arr.push({ $and: value });
306
+ }
307
+ else {
308
+ arr.push({ $or: value });
309
+ }
310
+ });
311
+ console.log("🚀 ~ file: query-parser.ts:303 ~ Object.entries ~ arr:", arr);
312
+ return arr;
313
+ };
314
+ var queryToMongo = function (query, requiredExternal, externalParams, constants, currentUser, currentTenant) {
315
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z;
316
+ if (currentUser === void 0) { currentUser = {}; }
317
+ if (currentTenant === void 0) { currentTenant = {}; }
318
+ var fieldValue = replaceExternalParams(query, requiredExternal, externalParams, constants, currentUser, currentTenant);
319
+ if (["undefined", "null", null, undefined, ""].includes(fieldValue)) {
320
+ //TODO: In case field is not present in old record then fieldValue is undefined
321
+ //TODO: In case of this, we assign some random string to avoid resulting all values
322
+ //TODO: This is use case in Spot Factor Project, where a new user with blank value able to see all records
323
+ //TODO: Discussed on meet
324
+ fieldValue = "random_string_since_field_not_present_" + moment_1.default(1318874398806).valueOf();
325
+ }
326
+ console.log("fieldValue queryToMongo 1", fieldValue);
327
+ var isDate = checkDate(fieldValue);
328
+ console.log("isDate queryToMongo 2", isDate);
329
+ var key = query.key, field = query.field, value = query.value, fieldType = query.fieldType;
330
+ if (isDate)
331
+ fieldValue = new Date(fieldValue);
332
+ console.log("fieldValue queryToMongo 1", fieldValue);
333
+ var condition = [
334
+ "dynamic_option",
335
+ "reference",
336
+ "static_option",
337
+ "belongsTo",
338
+ ].includes(fieldType);
339
+ if (condition && key === drapcode_constant_1.EQUALS && !isDate) {
340
+ if (!Array.isArray(fieldValue)) {
341
+ fieldValue = [fieldValue];
342
+ }
343
+ return _a = {}, _a[field] = { $in: fieldValue || [] }, _a;
344
+ }
345
+ if (condition && key === drapcode_constant_1.NOT_EQUAL && !isDate) {
346
+ if (!Array.isArray(fieldValue)) {
347
+ fieldValue = [fieldValue];
348
+ }
349
+ return _b = {}, _b[field] = { $nin: fieldValue || [] }, _b;
350
+ }
351
+ if (condition && key === drapcode_constant_1.IS_NULL) {
352
+ return _c = {}, _c[field] = { $type: "array", $eq: [] }, _c;
353
+ }
354
+ if (condition && key === drapcode_constant_1.IS_NOT_NULL) {
355
+ return _d = {}, _d[field] = { $exists: true, $type: "array", $ne: [] }, _d;
356
+ }
357
+ if (key === drapcode_constant_1.IS_NOT_NULL)
358
+ return _e = {}, _e[field] = { $nin: [null, ""] }, _e;
359
+ if (key === drapcode_constant_1.IS_NULL)
360
+ return _f = {}, _f[field] = { $in: [null, ""] }, _f;
361
+ if (key === drapcode_constant_1.LIKE)
362
+ return _g = {}, _g[field] = { $regex: fieldValue, $options: "i" }, _g;
363
+ if (key === drapcode_constant_1.GREATER_THAN_EQUALS_TO)
364
+ return _h = {}, _h[field] = { $gte: isDate ? fieldValue : +fieldValue }, _h;
365
+ if (key === drapcode_constant_1.LESS_THAN_EQUALS_TO)
366
+ return _j = {}, _j[field] = { $lte: isDate ? fieldValue : +fieldValue }, _j;
367
+ if (key === drapcode_constant_1.LESS_THAN)
368
+ return _k = {}, _k[field] = { $lt: isDate ? fieldValue : +fieldValue }, _k;
369
+ if (key === drapcode_constant_1.GREATER_THAN)
370
+ return _l = {}, _l[field] = { $gt: isDate ? fieldValue : +fieldValue }, _l;
371
+ if (key === drapcode_constant_1.IN_LIST) {
372
+ if (!Array.isArray(fieldValue)) {
373
+ fieldValue = [fieldValue];
374
+ }
375
+ return _m = {}, _m[field] = { $in: fieldValue || [] }, _m;
376
+ }
377
+ if (key === drapcode_constant_1.NOT_IN_LIST) {
378
+ if (!Array.isArray(fieldValue)) {
379
+ fieldValue = [fieldValue];
380
+ }
381
+ return _o = {}, _o[field] = { $nin: fieldValue || [] }, _o;
382
+ }
383
+ if (key === drapcode_constant_1.EQUALS && isDate) {
384
+ if (drapcode_constant_1.DateConstant.some(function (cnst) { return value.includes(cnst); })) {
385
+ return _p = {},
386
+ _p[field] = {
387
+ $gte: fieldValue,
388
+ },
389
+ _p;
390
+ }
391
+ else {
392
+ //TODO: Handle timezone here
393
+ return _q = {},
394
+ _q[field] = {
395
+ $gte: fieldValue,
396
+ $lt: new Date(date_util_1.nextDayDate(fieldValue)),
397
+ },
398
+ _q;
399
+ }
400
+ }
401
+ if (key == drapcode_constant_1.EQUALS && field === "createdBy")
402
+ return {
403
+ $and: [
404
+ (_r = {}, _r[field] = { $ne: null }, _r),
405
+ (_s = {}, _s[field] = { $ne: "" }, _s),
406
+ (_t = {}, _t[field] = { $eq: fieldValue }, _t),
407
+ ],
408
+ };
409
+ if (key == drapcode_constant_1.EQUALS && fieldType === "boolean" && fieldValue)
410
+ return JSON.parse(fieldValue)
411
+ ? (_u = {},
412
+ _u[field] = JSON.parse(fieldValue),
413
+ _u) : {
414
+ $or: [
415
+ (_v = {}, _v[field] = JSON.parse(fieldValue), _v),
416
+ (_w = {}, _w[field] = { $exists: false }, _w),
417
+ ],
418
+ };
419
+ if (key == drapcode_constant_1.EQUALS) {
420
+ return _x = {},
421
+ _x[field] = fieldType === "boolean" && fieldValue
422
+ ? JSON.parse(fieldValue)
423
+ : !isNaN(fieldValue)
424
+ ? +fieldValue
425
+ : fieldValue,
426
+ _x;
427
+ }
428
+ if (key == drapcode_constant_1.NOT_EQUAL)
429
+ return _y = {},
430
+ _y[field] = {
431
+ $ne: fieldType === "boolean" && fieldValue
432
+ ? JSON.parse(fieldValue)
433
+ : fieldValue,
434
+ },
435
+ _y;
436
+ if (key == drapcode_constant_1.BETWEEN) {
437
+ var _0 = exports.getMinMaxValue(fieldValue), startValue = _0.startValue, endValue = _0.endValue, isInteger = _0.isInteger;
438
+ return _z = {},
439
+ _z[field] = {
440
+ $gte: isInteger ? +startValue : startValue,
441
+ $lte: isInteger ? +endValue : endValue,
442
+ },
443
+ _z;
444
+ }
445
+ };
446
+ var isEntityInCondition = function (value) {
447
+ var isEntity = false;
448
+ if (value && Array.isArray(value)) {
449
+ value.forEach(function (val) {
450
+ if (typeof val === "string" || val instanceof String)
451
+ isEntity = val.startsWith("ENTITY::");
452
+ });
453
+ }
454
+ else {
455
+ if (value && (typeof value === "string" || value instanceof String))
456
+ isEntity = value.startsWith("ENTITY::");
457
+ }
458
+ return isEntity;
459
+ };
460
+ exports.isEntityInCondition = isEntityInCondition;
461
+ var replaceExternalParams = function (query, requiredExternal, externalParams, constants, currentUser, currentTenant) {
462
+ var key = query.key, value = query.value, fieldType = query.fieldType;
463
+ if (fieldType &&
464
+ !requiredExternal &&
465
+ ["dynamic_option", "reference", "static_option", "belongsTo"].includes(fieldType)) {
466
+ return value === drapcode_constant_1.CURRENT_USER ? currentUser["uuid"] : value;
467
+ }
468
+ if (fieldType &&
469
+ fieldType === "boolean" &&
470
+ ["true", "false", "", true, false].includes(value)) {
471
+ return "" + value;
472
+ }
473
+ if (key === drapcode_constant_1.IN_LIST || key === drapcode_constant_1.NOT_IN_LIST) {
474
+ var valueList_1 = [];
475
+ if (value && Array.isArray(value)) {
476
+ value.forEach(function (val) { return valueList_1.push(val); });
477
+ constants.forEach(function (constant) {
478
+ value.forEach(function (val) {
479
+ if (val === constant.name)
480
+ valueList_1.push(constant.value);
481
+ });
482
+ });
483
+ }
484
+ return valueList_1;
485
+ }
486
+ if (key === drapcode_constant_1.BETWEEN) {
487
+ var _a = exports.getMinMaxValue(value), startValue_1 = _a.startValue, endValue_1 = _a.endValue, isInteger = _a.isInteger;
488
+ if (requiredExternal) {
489
+ startValue_1 = "" + externalParams[startValue_1];
490
+ endValue_1 = "" + externalParams[endValue_1];
491
+ }
492
+ else {
493
+ if (__spreadArrays([drapcode_constant_1.CURRENT_USER], drapcode_constant_1.DateConstant).some(function (cnst) {
494
+ return startValue_1.includes(cnst);
495
+ })) {
496
+ startValue_1 = getValueOfProjectConstant(startValue_1, currentUser);
497
+ }
498
+ else {
499
+ startValue_1 = constants.filter(function (constant) { return constant.name == startValue_1; });
500
+ }
501
+ if (__spreadArrays([drapcode_constant_1.CURRENT_USER], drapcode_constant_1.DateConstant).some(function (cnst) { return endValue_1.includes(cnst); })) {
502
+ endValue_1 = getValueOfProjectConstant(endValue_1, currentUser);
503
+ }
504
+ else {
505
+ endValue_1 = constants.filter(function (constant) { return constant.name == endValue_1; });
506
+ }
507
+ }
508
+ //TODO: Need to test constant from collection and when this below if will run
509
+ if (Array.isArray(startValue_1)) {
510
+ startValue_1 = startValue_1[0].value;
511
+ }
512
+ if (Array.isArray(endValue_1)) {
513
+ endValue_1 = endValue_1[0].value;
514
+ }
515
+ //TODO: Need to figure out the params should be treated as number/string
516
+ if (!isNaN(startValue_1)) {
517
+ return startValue_1 + "---" + endValue_1 + "^";
518
+ }
519
+ else
520
+ return startValue_1 + "---" + endValue_1;
521
+ }
522
+ console.log("==> value", value);
523
+ console.log("==> currentUser", currentUser);
524
+ if (value.includes(drapcode_constant_1.CURRENT_USER)) {
525
+ if (value === drapcode_constant_1.CURRENT_USER) {
526
+ return currentUser["uuid"];
527
+ }
528
+ var splitValues = value.split("::");
529
+ console.log("splitValues", splitValues);
530
+ var refCollection = "", refCollectionField = "";
531
+ if (splitValues.length > 2) {
532
+ refCollection = splitValues[1];
533
+ refCollectionField = splitValues[2];
534
+ }
535
+ else if (splitValues.length === 2) {
536
+ refCollection = splitValues[0];
537
+ refCollectionField = splitValues[1];
538
+ }
539
+ else {
540
+ refCollection = splitValues[0];
541
+ refCollectionField = "";
542
+ }
543
+ console.log("refCollection", refCollection);
544
+ console.log("refCollectionField", refCollectionField);
545
+ console.log("first", refCollectionField && refCollection);
546
+ if (refCollection && refCollectionField) {
547
+ console.log("I have refCollection and Field");
548
+ if (refCollection === drapcode_constant_1.CURRENT_USER) {
549
+ return currentUser[refCollectionField];
550
+ }
551
+ else {
552
+ var refCollectionData = currentUser[refCollection];
553
+ if (!refCollectionData) {
554
+ return "";
555
+ }
556
+ if (refCollectionData.length > 1) {
557
+ //TODO: Need to handle multi ref
558
+ return "";
559
+ }
560
+ refCollectionData = refCollectionData[0];
561
+ console.log("refCollectionData[refCollectionField]", refCollectionData[refCollectionField]);
562
+ return refCollectionData[refCollectionField];
563
+ }
564
+ }
565
+ //this means that data has to be match with currnet user field that is not ref type
566
+ if (refCollection) {
567
+ return currentUser[refCollection];
568
+ }
569
+ return currentUser["uuid"];
570
+ }
571
+ if (value.includes(drapcode_constant_1.CURRENT_TENANT)) {
572
+ if (value === drapcode_constant_1.CURRENT_TENANT) {
573
+ return currentTenant["uuid"];
574
+ }
575
+ var splitValues = value.split("::");
576
+ console.log("splitValues", splitValues);
577
+ var refCollection = "", refCollectionField = "";
578
+ if (splitValues.length > 2) {
579
+ refCollection = splitValues[1];
580
+ refCollectionField = splitValues[2];
581
+ }
582
+ else if (splitValues.length === 2) {
583
+ refCollection = splitValues[0];
584
+ refCollectionField = splitValues[1];
585
+ }
586
+ else {
587
+ refCollection = splitValues[0];
588
+ refCollectionField = "";
589
+ }
590
+ console.log("\n refCollection", refCollection);
591
+ console.log("\n refCollectionField", refCollectionField);
592
+ if (refCollection && refCollectionField) {
593
+ console.log("I have refCollection and Field");
594
+ if (refCollection === "CURRENT_TENANT") {
595
+ return currentTenant[refCollectionField];
596
+ }
597
+ else {
598
+ var refCollectionData = currentTenant[refCollection];
599
+ console.log("\n refCollectionData", refCollectionData);
600
+ if (!refCollectionData)
601
+ return "";
602
+ if (refCollectionData.length > 1)
603
+ return "";
604
+ refCollectionData = refCollectionData[0];
605
+ return refCollectionData[refCollectionField];
606
+ }
607
+ }
608
+ //this means that data has to be match with currnet user field that is not ref type
609
+ if (refCollection)
610
+ return currentTenant[refCollection];
611
+ return currentTenant["uuid"];
612
+ }
613
+ if (drapcode_constant_1.DateConstant.some(function (cnst) { return value.includes(cnst); })) {
614
+ return getValueOfProjectConstant(value, {});
615
+ }
616
+ if (exports.isEntityInCondition(value)) {
617
+ var key_1 = value.replace("ENTITY::", "");
618
+ return externalParams[key_1] ? externalParams[key_1] : "";
619
+ }
620
+ //TODO: This is just to confirm if external then it should be get from externalParams
621
+ if (requiredExternal) {
622
+ //TODO: Value returns from here undefined.
623
+ var externalParamValue = externalParams["" + value];
624
+ if (!isNaN(externalParamValue)) {
625
+ return +externalParamValue;
626
+ }
627
+ return externalParams["" + value];
628
+ }
629
+ var constantArr = constants.filter(function (constant) { return constant.name == value; });
630
+ return constantArr.length ? "" + constantArr[0].value : "";
631
+ };
632
+ var checkDate = function (queryValue) {
633
+ return ("" + queryValue).match(date_util_1.DATE_REGEX);
634
+ };
635
+ var getMinMaxValue = function (value) {
636
+ var isValid = value && value.includes("---");
637
+ if (isValid) {
638
+ var isInteger = value.includes("^");
639
+ var result = value.split("---");
640
+ var endValue = result[1];
641
+ if (isInteger && result.length)
642
+ endValue = endValue.slice(0, -1);
643
+ return { startValue: result[0], endValue: endValue, isInteger: isInteger };
644
+ }
645
+ else {
646
+ return { startValue: "", endValue: "" };
647
+ }
648
+ };
649
+ exports.getMinMaxValue = getMinMaxValue;
650
+ var getValueOfProjectConstant = function (value, currentUser) {
651
+ if (value === drapcode_constant_1.CURRENT_USER)
652
+ return currentUser["uuid"];
653
+ if (value === drapcode_constant_1.CURRENT_DATE)
654
+ return date_util_1.createLoggerDateFormat();
655
+ if ([drapcode_constant_1.CURRENT_TIME, drapcode_constant_1.CURRENT_DATE_TIME].includes(value))
656
+ return date_util_1.createLogsDateFormat();
657
+ if (drapcode_constant_1.DateTimeUnit.some(function (cnst) { return value.includes(cnst); }))
658
+ return date_util_1.getDateValue(value);
659
+ };
660
+ var getSearchObjQuery = function (searchObj, searchQueryTypeObj, timezone) {
661
+ var searchAggregateQuery = [];
662
+ var likeQuery = [];
663
+ Object.entries(searchObj).forEach(function (_a) {
664
+ var _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
665
+ var key = _a[0], value = _a[1];
666
+ if (value) {
667
+ var searchQueryTypeKey = searchQueryTypeObj[key];
668
+ if (searchQueryTypeKey) {
669
+ if (searchQueryTypeKey === "boolean") {
670
+ // if input is string and db field type is boolean
671
+ searchAggregateQuery.push({
672
+ $addFields: (_b = {},
673
+ _b["_" + key] = "$" + key,
674
+ _b),
675
+ });
676
+ likeQuery.push((_c = {},
677
+ _c["_" + key] = toBoolean(value),
678
+ _c));
679
+ }
680
+ else if ([
681
+ "static_option",
682
+ "dynamic_option",
683
+ "reference",
684
+ "belongsTo",
685
+ ].includes(searchQueryTypeKey)) {
686
+ // if input is string and db field type is array
687
+ searchAggregateQuery.push({
688
+ $addFields: (_d = {},
689
+ _d["_" + key] = "$" + key,
690
+ _d),
691
+ });
692
+ likeQuery.push((_e = {},
693
+ _e["_" + key] = { $all: [value] },
694
+ _e));
695
+ }
696
+ else if (searchQueryTypeKey === "tel") {
697
+ // handling value when db field type is tel
698
+ searchAggregateQuery.push({
699
+ $addFields: (_f = {},
700
+ _f["_" + key] = { $toString: "$" + key },
701
+ _f),
702
+ });
703
+ likeQuery.push((_g = {},
704
+ _g["_" + key] = {
705
+ $regex: value.startsWith("+") ? value.replace("+", "") : value,
706
+ $options: "i",
707
+ },
708
+ _g));
709
+ }
710
+ else if (searchQueryTypeKey === "number") {
711
+ // handling value when db field type is Double/Int
712
+ searchAggregateQuery.push({
713
+ $addFields: (_h = {},
714
+ _h["_" + key] = { $toString: { $toLong: "$" + key } },
715
+ _h),
716
+ });
717
+ likeQuery.push((_j = {},
718
+ _j["_" + key] = {
719
+ $regex: value,
720
+ $options: "i",
721
+ },
722
+ _j));
723
+ }
724
+ else if (["date", "createdAt"].includes(searchQueryTypeKey)) {
725
+ if (key.startsWith("start_") || key.startsWith("end_")) {
726
+ var fieldKey = key.replace("start_", "");
727
+ fieldKey = fieldKey.replace("end_", "");
728
+ searchAggregateQuery.push({
729
+ $addFields: (_k = {},
730
+ _k["_" + key] = { $toString: "$" + fieldKey },
731
+ _k),
732
+ });
733
+ if (key.startsWith("start_")) {
734
+ likeQuery.push((_l = {},
735
+ _l["_" + key] = {
736
+ $gte: date_util_1.timezoneDateParse(value, false, true),
737
+ },
738
+ _l));
739
+ }
740
+ else if (key.startsWith("end_")) {
741
+ likeQuery.push((_m = {},
742
+ _m["_" + key] = {
743
+ $lt: date_util_1.timezoneDateParse(value, true),
744
+ },
745
+ _m));
746
+ }
747
+ }
748
+ }
749
+ else {
750
+ // if input is string and db field type is number
751
+ // converting db field to string first
752
+ searchAggregateQuery.push({
753
+ $addFields: (_o = {},
754
+ _o["_" + key] = { $toString: "$" + key },
755
+ _o),
756
+ });
757
+ likeQuery.push((_p = {},
758
+ _p["_" + key] = {
759
+ $regex: value,
760
+ $options: "i",
761
+ },
762
+ _p));
763
+ }
764
+ }
765
+ else {
766
+ likeQuery.push((_q = {},
767
+ _q[key] = {
768
+ $regex: value,
769
+ $options: "i",
770
+ },
771
+ _q));
772
+ }
773
+ }
774
+ });
775
+ console.log("==> searchAggregateQuery", JSON.stringify(searchAggregateQuery));
776
+ console.log("==> likeQuery", JSON.stringify(likeQuery));
777
+ return { searchAggregateQuery: searchAggregateQuery, likeQuery: likeQuery };
778
+ };