@resolveio/server-lib 20.0.26 → 20.0.28

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 (201) hide show
  1. package/client-server-app.js +1 -47
  2. package/client-server-app.js.map +1 -1
  3. package/collections/app-status.collection.js +1 -50
  4. package/collections/app-status.collection.js.map +1 -1
  5. package/collections/counter.collection.js +1 -53
  6. package/collections/counter.collection.js.map +1 -1
  7. package/collections/cron-job-history.collection.js +1 -88
  8. package/collections/cron-job-history.collection.js.map +1 -1
  9. package/collections/cron-job.collection.js +1 -84
  10. package/collections/cron-job.collection.js.map +1 -1
  11. package/collections/email-history.collection.js +1 -65
  12. package/collections/email-history.collection.js.map +1 -1
  13. package/collections/email-verified.collection.js +1 -60
  14. package/collections/email-verified.collection.js.map +1 -1
  15. package/collections/file.collection.js +1 -72
  16. package/collections/file.collection.js.map +1 -1
  17. package/collections/flag.collection.js +1 -55
  18. package/collections/flag.collection.js.map +1 -1
  19. package/collections/log-method-latency.collection.js +1 -63
  20. package/collections/log-method-latency.collection.js.map +1 -1
  21. package/collections/log-subscription.collection.js +1 -67
  22. package/collections/log-subscription.collection.js.map +1 -1
  23. package/collections/log-ts.collection.js +1 -77
  24. package/collections/log-ts.collection.js.map +1 -1
  25. package/collections/log.collection.js +1 -76
  26. package/collections/log.collection.js.map +1 -1
  27. package/collections/logged-in-users.collection.js +1 -64
  28. package/collections/logged-in-users.collection.js.map +1 -1
  29. package/collections/method-response.collection.js +1 -65
  30. package/collections/method-response.collection.js.map +1 -1
  31. package/collections/monitor-cpu.collection.js +1 -62
  32. package/collections/monitor-cpu.collection.js.map +1 -1
  33. package/collections/monitor-memory.collection.js +1 -74
  34. package/collections/monitor-memory.collection.js.map +1 -1
  35. package/collections/monitor-mongo.collection.js +1 -68
  36. package/collections/monitor-mongo.collection.js.map +1 -1
  37. package/collections/notification.collection.js +1 -55
  38. package/collections/notification.collection.js.map +1 -1
  39. package/collections/report-builder-dashboard-builder.collection.js +1 -108
  40. package/collections/report-builder-dashboard-builder.collection.js.map +1 -1
  41. package/collections/report-builder-library.collection.js +1 -86
  42. package/collections/report-builder-library.collection.js.map +1 -1
  43. package/collections/report-builder-report.collection.js +1 -148
  44. package/collections/report-builder-report.collection.js.map +1 -1
  45. package/collections/user-group.collection.js +1 -93
  46. package/collections/user-group.collection.js.map +1 -1
  47. package/collections/user-guide.collection.js +1 -56
  48. package/collections/user-guide.collection.js.map +1 -1
  49. package/collections/user.collection.js +1 -265
  50. package/collections/user.collection.js.map +1 -1
  51. package/cron/cron.js +1 -101
  52. package/cron/cron.js.map +1 -1
  53. package/fixtures/cron-jobs.js +1 -87
  54. package/fixtures/cron-jobs.js.map +1 -1
  55. package/fixtures/init.js +1 -58
  56. package/fixtures/init.js.map +1 -1
  57. package/http/auth.js +1 -763
  58. package/http/auth.js.map +1 -1
  59. package/http/health.js +1 -11
  60. package/http/health.js.map +1 -1
  61. package/http/home.js +1 -65
  62. package/http/home.js.map +1 -1
  63. package/index.js +1 -126
  64. package/index.js.map +1 -1
  65. package/managers/cron.manager.js +1 -322
  66. package/managers/cron.manager.js.map +1 -1
  67. package/managers/method.manager.js +1 -593
  68. package/managers/method.manager.js.map +1 -1
  69. package/managers/mongo.manager.js +1 -2259
  70. package/managers/mongo.manager.js.map +1 -1
  71. package/managers/monitor.manager.js +1 -350
  72. package/managers/monitor.manager.js.map +1 -1
  73. package/managers/subscription.manager.js +1 -1110
  74. package/managers/subscription.manager.js.map +1 -1
  75. package/managers/subscription.performance.js +1 -102
  76. package/managers/subscription.performance.js.map +1 -1
  77. package/methods/accounts.js +1 -291
  78. package/methods/accounts.js.map +1 -1
  79. package/methods/aws.js +1 -616
  80. package/methods/aws.js.map +1 -1
  81. package/methods/collections.js +1 -499
  82. package/methods/collections.js.map +1 -1
  83. package/methods/counters.js +1 -121
  84. package/methods/counters.js.map +1 -1
  85. package/methods/cron-jobs.js +1 -1337
  86. package/methods/cron-jobs.js.map +1 -1
  87. package/methods/flags.js +1 -8
  88. package/methods/flags.js.map +1 -1
  89. package/methods/logs.js +1 -370
  90. package/methods/logs.js.map +1 -1
  91. package/methods/monitor.js +1 -564
  92. package/methods/monitor.js.map +1 -1
  93. package/methods/pdf.js +1 -731
  94. package/methods/pdf.js.map +1 -1
  95. package/methods/report-builder.js +1 -859
  96. package/methods/report-builder.js.map +1 -1
  97. package/methods/support.js +1 -245
  98. package/methods/support.js.map +1 -1
  99. package/models/app-status.model.js +1 -3
  100. package/models/app-status.model.js.map +1 -1
  101. package/models/billing-logged-in-users.model.js +1 -3
  102. package/models/billing-logged-in-users.model.js.map +1 -1
  103. package/models/collection-document.model.js +1 -3
  104. package/models/collection-document.model.js.map +1 -1
  105. package/models/counter.model.js +1 -3
  106. package/models/counter.model.js.map +1 -1
  107. package/models/cron-job-history.model.js +1 -3
  108. package/models/cron-job-history.model.js.map +1 -1
  109. package/models/cron-job.model.js +1 -3
  110. package/models/cron-job.model.js.map +1 -1
  111. package/models/dialog.model.js +1 -3
  112. package/models/dialog.model.js.map +1 -1
  113. package/models/email-history.model.js +1 -3
  114. package/models/email-history.model.js.map +1 -1
  115. package/models/email-verified.model.js +1 -3
  116. package/models/email-verified.model.js.map +1 -1
  117. package/models/file.model.js +1 -3
  118. package/models/file.model.js.map +1 -1
  119. package/models/flag.model.js +1 -3
  120. package/models/flag.model.js.map +1 -1
  121. package/models/log-method-latency.model.js +1 -3
  122. package/models/log-method-latency.model.js.map +1 -1
  123. package/models/log-subscription.model.js +1 -3
  124. package/models/log-subscription.model.js.map +1 -1
  125. package/models/log.model.js +1 -3
  126. package/models/log.model.js.map +1 -1
  127. package/models/logged-in-users.model.js +1 -3
  128. package/models/logged-in-users.model.js.map +1 -1
  129. package/models/method-response.model.js +1 -3
  130. package/models/method-response.model.js.map +1 -1
  131. package/models/method.model.js +1 -3
  132. package/models/method.model.js.map +1 -1
  133. package/models/monitor-cpu.model.js +1 -3
  134. package/models/monitor-cpu.model.js.map +1 -1
  135. package/models/monitor-memory.model.js +1 -3
  136. package/models/monitor-memory.model.js.map +1 -1
  137. package/models/monitor-mongo.model.js +1 -3
  138. package/models/monitor-mongo.model.js.map +1 -1
  139. package/models/notification.model.js +1 -3
  140. package/models/notification.model.js.map +1 -1
  141. package/models/pagination.model.js +1 -23
  142. package/models/pagination.model.js.map +1 -1
  143. package/models/permission.model.js +1 -3
  144. package/models/permission.model.js.map +1 -1
  145. package/models/report-builder-dashboard-builder.model.js +1 -3
  146. package/models/report-builder-dashboard-builder.model.js.map +1 -1
  147. package/models/report-builder-library.model.js +1 -3
  148. package/models/report-builder-library.model.js.map +1 -1
  149. package/models/report-builder-report.model.js +1 -3
  150. package/models/report-builder-report.model.js.map +1 -1
  151. package/models/report-builder.model.js +1 -3
  152. package/models/report-builder.model.js.map +1 -1
  153. package/models/select-data-label.model.js +1 -3
  154. package/models/select-data-label.model.js.map +1 -1
  155. package/models/server-response.model.js +1 -3
  156. package/models/server-response.model.js.map +1 -1
  157. package/models/subscription.model.js +1 -3
  158. package/models/subscription.model.js.map +1 -1
  159. package/models/support-ticket.model.js +1 -3
  160. package/models/support-ticket.model.js.map +1 -1
  161. package/models/user-group.model.js +1 -3
  162. package/models/user-group.model.js.map +1 -1
  163. package/models/user-guide.model.js +1 -3
  164. package/models/user-guide.model.js.map +1 -1
  165. package/models/user.model.js +1 -3
  166. package/models/user.model.js.map +1 -1
  167. package/package.json +6 -4
  168. package/public_api.js +1 -74
  169. package/public_api.js.map +1 -1
  170. package/publications/app-status.js +1 -16
  171. package/publications/app-status.js.map +1 -1
  172. package/publications/cron-jobs.js +1 -32
  173. package/publications/cron-jobs.js.map +1 -1
  174. package/publications/files.js +1 -36
  175. package/publications/files.js.map +1 -1
  176. package/publications/flags.js +1 -22
  177. package/publications/flags.js.map +1 -1
  178. package/publications/logs.js +1 -164
  179. package/publications/logs.js.map +1 -1
  180. package/publications/method-responses.js +1 -16
  181. package/publications/method-responses.js.map +1 -1
  182. package/publications/notifications.js +1 -16
  183. package/publications/notifications.js.map +1 -1
  184. package/publications/report-builder-dashboard-builders.js +1 -42
  185. package/publications/report-builder-dashboard-builders.js.map +1 -1
  186. package/publications/report-builder-libraries.js +1 -89
  187. package/publications/report-builder-libraries.js.map +1 -1
  188. package/publications/report-builder-reports.js +1 -50
  189. package/publications/report-builder-reports.js.map +1 -1
  190. package/publications/super-admin.js +1 -16
  191. package/publications/super-admin.js.map +1 -1
  192. package/publications/user-groups.js +1 -16
  193. package/publications/user-groups.js.map +1 -1
  194. package/publications/user-guides.js +1 -16
  195. package/publications/user-guides.js.map +1 -1
  196. package/server-app.js +1 -770
  197. package/server-app.js.map +1 -1
  198. package/util/common.js +1 -546
  199. package/util/common.js.map +1 -1
  200. package/util/schema-report-builder.js +1 -452
  201. package/util/schema-report-builder.js.map +1 -1
@@ -1,2260 +1,2 @@
1
- "use strict";
2
- var __extends = (this && this.__extends) || (function () {
3
- var extendStatics = function (d, b) {
4
- extendStatics = Object.setPrototypeOf ||
5
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
- return extendStatics(d, b);
8
- };
9
- return function (d, b) {
10
- if (typeof b !== "function" && b !== null)
11
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
- extendStatics(d, b);
13
- function __() { this.constructor = d; }
14
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
- };
16
- })();
17
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
18
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
19
- return new (P || (P = Promise))(function (resolve, reject) {
20
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
21
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
22
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
23
- step((generator = generator.apply(thisArg, _arguments || [])).next());
24
- });
25
- };
26
- var __generator = (this && this.__generator) || function (thisArg, body) {
27
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
28
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
29
- function verb(n) { return function (v) { return step([n, v]); }; }
30
- function step(op) {
31
- if (f) throw new TypeError("Generator is already executing.");
32
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
33
- 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;
34
- if (y = 0, t) op = [op[0] & 2, t.value];
35
- switch (op[0]) {
36
- case 0: case 1: t = op; break;
37
- case 4: _.label++; return { value: op[1], done: false };
38
- case 5: _.label++; y = op[1]; op = [0]; continue;
39
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
40
- default:
41
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
42
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
43
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
44
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
45
- if (t[2]) _.ops.pop();
46
- _.trys.pop(); continue;
47
- }
48
- op = body.call(thisArg, _);
49
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
50
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
51
- }
52
- };
53
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
54
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
55
- if (ar || !(i in from)) {
56
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
57
- ar[i] = from[i];
58
- }
59
- }
60
- return to.concat(ar || Array.prototype.slice.call(from));
61
- };
62
- Object.defineProperty(exports, "__esModule", { value: true });
63
- exports.objectIdHexString = exports.MongoManagerUserCollection = exports.MongoManagerCollection = exports.MongoManagerModel = exports.MongoManager = void 0;
64
- var simpl_schema_1 = require("simpl-schema");
65
- var mongodb_1 = require("mongodb");
66
- var index_1 = require("../index");
67
- var user_collection_1 = require("../collections/user.collection");
68
- var common_1 = require("../util/common");
69
- var log_collection_1 = require("../collections/log.collection");
70
- var NodeCache = require("node-cache");
71
- var crypto = require('crypto');
72
- var scmp = require('scmp');
73
- var monitor_manager_1 = require("./monitor.manager");
74
- var os_1 = require("os");
75
- var numCPUs = (0, os_1.cpus)().length;
76
- var v8 = require('v8');
77
- var async_1 = require("async");
78
- var MongoManager = /** @class */ (function () {
79
- function MongoManager() {
80
- var _this = this;
81
- this._collections = [];
82
- this._mongoQueue = [];
83
- this._mongoQueueId = 0;
84
- this._mongoQueueRunning = false;
85
- this._mongoQueueCacheId = 1;
86
- this._heapStats = v8.getHeapStatistics();
87
- this._heapLimit = this._heapStats.heap_size_limit / numCPUs / 8;
88
- this._serverCollections = [];
89
- this._debugMongoQueueHits = 0;
90
- this._debugRemoveCacheHits = 0;
91
- this._debugMongoQueueCollections = [];
92
- this._nodeCache = new NodeCache({ stdTTL: 0, checkperiod: 0 });
93
- setInterval(function () {
94
- if (index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()) {
95
- console.log(new Date(), 'Mongo Manager', 'Collections', _this._collections.length);
96
- console.log(new Date(), 'Mongo Manager', 'Mongo Queue', _this._mongoQueue.length, JSON.stringify(_this._mongoQueue.sort(function (a, b) { return a.name_collection.localeCompare(b.name_collection); }), null, 2));
97
- console.log(new Date(), 'Mongo Manager', 'Server Collections', _this._serverCollections.length);
98
- console.log(new Date(), 'Mongo Manager', 'Mongo Queue Hits', _this._debugMongoQueueHits);
99
- console.log(new Date(), 'Mongo Manager', 'Mongo Queue Collections', _this._debugMongoQueueCollections.sort(function (a, b) { return a.collection.localeCompare(b.collection) || a.function.localeCompare(b.function); }));
100
- console.log(new Date(), 'Mongo Manager', 'Cache Cleanup Hits', JSON.stringify(_this._debugRemoveCacheHits, null, 2));
101
- }
102
- _this._debugMongoQueueHits = 0;
103
- _this._debugRemoveCacheHits = 0;
104
- _this._debugMongoQueueCollections = [];
105
- }, 60000);
106
- this.initServerCollections();
107
- this.runQueue();
108
- }
109
- MongoManager.prototype.initServerCollections = function () {
110
- return __awaiter(this, void 0, void 0, function () {
111
- var collections;
112
- return __generator(this, function (_a) {
113
- switch (_a.label) {
114
- case 0: return [4 /*yield*/, index_1.ResolveIOServer.getMainDB().listCollections().toArray()];
115
- case 1:
116
- collections = _a.sent();
117
- this._serverCollections = collections;
118
- return [2 /*return*/];
119
- }
120
- });
121
- });
122
- };
123
- MongoManager.prototype.getServerCollections = function () {
124
- return this._serverCollections;
125
- };
126
- MongoManager.prototype.registerCollection = function (collection) {
127
- var _this = this;
128
- if (collection.collectionOptions && collection.collectionOptions.timeseries && collection.collectionOptions.timeseries.timeField && this._serverCollections.some(function (a) { return a.name === collection.collectionName && a.type === 'collection'; })) {
129
- index_1.ResolveIOServer.getMainDB().dropCollection(collection.collectionName).then(function () {
130
- _this.createCollection(collection);
131
- });
132
- }
133
- this._collections.push(collection);
134
- };
135
- MongoManager.prototype.createCollection = function (collection) {
136
- index_1.ResolveIOServer.getMainDB().createCollection(collection.collectionName, collection.collectionOptions);
137
- };
138
- MongoManager.prototype.collections = function () {
139
- return this._collections;
140
- };
141
- MongoManager.prototype.collection = function (collectionName) {
142
- return this._collections.filter(function (a) { return a.collectionName === collectionName; })[0];
143
- };
144
- MongoManager.prototype.addToQueue = function (mongoQueue) {
145
- var _mongoQueue = this._mongoQueue.filter(function (a) { return a.name_collection === mongoQueue.name_collection && a.name_function === mongoQueue.name_function && a.name_function_addt === mongoQueue.name_function_addt && JSON.stringify(a.data_function) === JSON.stringify(mongoQueue.data_function) && JSON.stringify(a.data_function_addt) === JSON.stringify(mongoQueue.data_function_addt); })[0];
146
- if (_mongoQueue) {
147
- if (!_mongoQueue.running) {
148
- _mongoQueue.cbs.push(mongoQueue.cbs[0]);
149
- }
150
- else {
151
- _mongoQueue.cbs_next.push(mongoQueue.cbs[0]);
152
- }
153
- }
154
- else {
155
- mongoQueue._id = this._mongoQueueId;
156
- this._mongoQueueId += 1;
157
- this._mongoQueue.splice(0, 0, mongoQueue);
158
- }
159
- };
160
- MongoManager.prototype.runQueue = function () {
161
- return __awaiter(this, void 0, void 0, function () {
162
- var _this = this;
163
- return __generator(this, function (_a) {
164
- setInterval(function () {
165
- if (!_this._mongoQueueRunning) {
166
- var queueArr = _this._mongoQueue.filter(function (a) { return !a.running && a.cbs.length; });
167
- if (queueArr.length) {
168
- _this._mongoQueueRunning = true;
169
- var _loop_1 = function (i) {
170
- var _a, _b, _c;
171
- _this._debugMongoQueueHits += 1;
172
- var mongoQueue = queueArr[i];
173
- if (!_this._debugMongoQueueCollections.some(function (a) { return a.collection === mongoQueue.name_collection && a.function === mongoQueue.name_function; })) {
174
- _this._debugMongoQueueCollections.push({
175
- collection: mongoQueue.name_collection,
176
- function: mongoQueue.name_function,
177
- hits: 1
178
- });
179
- }
180
- else {
181
- _this._debugMongoQueueCollections.filter(function (a) { return a.collection === mongoQueue.name_collection && a.function === mongoQueue.name_function; })[0].hits += 1;
182
- }
183
- mongoQueue.running = true;
184
- mongoQueue.invalidateFlag = false;
185
- if (mongoQueue.cacheId) {
186
- try {
187
- var res_1 = JSON.parse(_this._nodeCache.get(mongoQueue.cacheId), common_1.dateReviver);
188
- mongoQueue.cbs.forEach(function (cb) {
189
- cb(null, res_1, true);
190
- });
191
- mongoQueue.cbs = [];
192
- mongoQueue.running = false;
193
- }
194
- catch (_d) {
195
- mongoQueue.cacheId = 0;
196
- }
197
- }
198
- if (!mongoQueue.cacheId) {
199
- if (!mongoQueue.name_function_addt) {
200
- var monitor_1 = new monitor_manager_1.MonitorMongo(mongoQueue.name_function, mongoQueue.name_collection, JSON.stringify(mongoQueue.data_function));
201
- (_a = index_1.ResolveIOServer.getMainDB().collection(mongoQueue.name_collection))[mongoQueue.name_function].apply(_a, mongoQueue.data_function).then(function (res) {
202
- monitor_1.finish();
203
- if (!mongoQueue.invalidateFlag) {
204
- mongoQueue.invalidateCount = 0;
205
- var stringifyLength = 0;
206
- var stringifyFail = false;
207
- try {
208
- var stringify = JSON.stringify(res).replace(/[\[\]\,\"]/g, '');
209
- stringifyLength = stringify.length;
210
- }
211
- catch (e) {
212
- stringifyFail = true;
213
- }
214
- if (!stringifyFail && res !== null && res !== undefined && (!Array.isArray(res) || res.length) && stringifyLength < 10000000) {
215
- mongoQueue.cacheId = _this._mongoQueueCacheId;
216
- _this._mongoQueueCacheId += 1;
217
- _this.addToCache(mongoQueue.cacheId, res);
218
- }
219
- else {
220
- mongoQueue.cacheId = 0;
221
- }
222
- mongoQueue.cbs.forEach(function (cb) {
223
- cb(null, res, false);
224
- });
225
- if (mongoQueue.cbs_next.length) {
226
- mongoQueue.cbs = mongoQueue.cbs_next;
227
- mongoQueue.cbs_next = [];
228
- }
229
- else {
230
- mongoQueue.cbs = [];
231
- }
232
- }
233
- else {
234
- if (mongoQueue.invalidateCount >= 5) {
235
- mongoQueue.invalidateCount = 0;
236
- mongoQueue.cbs.forEach(function (cb) {
237
- cb(null, res, false);
238
- });
239
- }
240
- mongoQueue.cbs = mongoQueue.cbs.concat(mongoQueue.cbs_next);
241
- mongoQueue.cbs_next = [];
242
- }
243
- mongoQueue.running = false;
244
- }, function (err) {
245
- monitor_1.finish();
246
- console.log.apply(console, __spreadArray(__spreadArray([new Date(), 'Error ' + mongoQueue.name_function, mongoQueue.name_collection], mongoQueue.data_function, false), [err], false));
247
- mongoQueue.cbs.forEach(function (cb) {
248
- cb(err, null, false);
249
- });
250
- mongoQueue.cbs_next.forEach(function (cb) {
251
- cb(err, null, false);
252
- });
253
- if (_this._mongoQueue.map(function (a) { return a._id; }).indexOf(mongoQueue._id) >= 0) {
254
- _this._mongoQueue.splice(_this._mongoQueue.map(function (a) { return a._id; }).indexOf(mongoQueue._id), 1);
255
- }
256
- });
257
- }
258
- else {
259
- var monitor_2 = new monitor_manager_1.MonitorMongo(mongoQueue.name_function, mongoQueue.name_collection, JSON.stringify(__spreadArray(__spreadArray(__spreadArray([], mongoQueue.data_function, true), [mongoQueue.name_function_addt], false), mongoQueue.data_function_addt, true)));
260
- (_b = (_c = index_1.ResolveIOServer.getMainDB().collection(mongoQueue.name_collection))[mongoQueue.name_function].apply(_c, mongoQueue.data_function))[mongoQueue.name_function_addt].apply(_b, mongoQueue.data_function_addt).then(function (res) {
261
- monitor_2.finish();
262
- if (!mongoQueue.invalidateFlag) {
263
- mongoQueue.invalidateCount = 0;
264
- var stringifyLength = 0;
265
- var stringifyFail = false;
266
- try {
267
- var stringify = JSON.stringify(res).replace(/[\[\]\,\"]/g, '');
268
- stringifyLength = stringify.length;
269
- }
270
- catch (e) {
271
- stringifyFail = true;
272
- }
273
- if (!stringifyFail && res !== null && res !== undefined && (!Array.isArray(res) || res.length) && stringifyLength < 10000000) {
274
- mongoQueue.cacheId = _this._mongoQueueCacheId;
275
- _this._mongoQueueCacheId += 1;
276
- _this.addToCache(mongoQueue.cacheId, res);
277
- }
278
- else {
279
- mongoQueue.cacheId = 0;
280
- }
281
- mongoQueue.cbs.forEach(function (cb) {
282
- cb(null, res, false);
283
- });
284
- if (mongoQueue.cbs_next.length) {
285
- mongoQueue.cbs = mongoQueue.cbs_next;
286
- mongoQueue.cbs_next = [];
287
- }
288
- else {
289
- mongoQueue.cbs = [];
290
- }
291
- }
292
- else {
293
- if (mongoQueue.invalidateCount >= 5) {
294
- mongoQueue.invalidateCount = 0;
295
- mongoQueue.cbs.forEach(function (cb) {
296
- cb(null, res, false);
297
- });
298
- }
299
- mongoQueue.cbs = mongoQueue.cbs.concat(mongoQueue.cbs_next);
300
- mongoQueue.cbs_next = [];
301
- }
302
- mongoQueue.running = false;
303
- }, function (err) {
304
- monitor_2.finish();
305
- mongoQueue.cbs.forEach(function (cb) {
306
- cb(err, null, false);
307
- });
308
- mongoQueue.cbs_next.forEach(function (cb) {
309
- cb(err, null, false);
310
- });
311
- if (_this._mongoQueue.map(function (a) { return a._id; }).indexOf(mongoQueue._id) >= 0) {
312
- _this._mongoQueue.splice(_this._mongoQueue.map(function (a) { return a._id; }).indexOf(mongoQueue._id), 1);
313
- }
314
- });
315
- }
316
- }
317
- };
318
- for (var i = queueArr.length - 1; i >= 0; i--) {
319
- _loop_1(i);
320
- }
321
- _this._mongoQueueRunning = false;
322
- }
323
- }
324
- }, 25);
325
- return [2 /*return*/];
326
- });
327
- });
328
- };
329
- MongoManager.prototype.addToCache = function (id, data) {
330
- var nodeCacheSize = this._nodeCache.getStats().vsize;
331
- if (nodeCacheSize > this._heapLimit) {
332
- var deleteCount = 0;
333
- var queueArr = this._mongoQueue.filter(function (a) { return a.cacheId && !a.running && !a.cbs.length; });
334
- for (var zz = queueArr.length - 1; zz >= 0; zz--) {
335
- this._debugRemoveCacheHits += 1;
336
- var queue = queueArr[zz];
337
- this._nodeCache.del(queue.cacheId);
338
- queue.cacheId = 0;
339
- if (this._mongoQueue.map(function (a) { return a._id; }).indexOf(queue._id) >= 0) {
340
- this._mongoQueue.splice(this._mongoQueue.map(function (a) { return a._id; }).indexOf(queue._id), 1);
341
- }
342
- deleteCount += 1;
343
- nodeCacheSize = this._nodeCache.getStats().vsize;
344
- if (nodeCacheSize < this._heapLimit * 0.75) {
345
- break;
346
- }
347
- }
348
- console.log('Query Cache: ' + 'Too Big, - Deleted: ' + deleteCount + ' - ' + nodeCacheSize);
349
- }
350
- this._nodeCache.set(id, JSON.stringify(data));
351
- };
352
- MongoManager.prototype.invalidateQueryCache = function (collection) {
353
- var queueArr = this._mongoQueue.filter(function (a) { return (a.name_collection === collection || a.lookup_collections.includes(collection)); });
354
- for (var i = queueArr.length - 1; i >= 0; i--) {
355
- var queue = queueArr[i];
356
- if (queue.cacheId) {
357
- this._nodeCache.del(queue.cacheId);
358
- queue.cacheId = 0;
359
- }
360
- if (queue.running) {
361
- queue.invalidateFlag = true;
362
- queue.invalidateCount += 1;
363
- }
364
- else if (!queue.cbs.length) {
365
- if (this._mongoQueue.map(function (a) { return a._id; }).indexOf(queue._id) >= 0) {
366
- this._mongoQueue.splice(this._mongoQueue.map(function (a) { return a._id; }).indexOf(queue._id), 1);
367
- }
368
- }
369
- }
370
- };
371
- return MongoManager;
372
- }());
373
- exports.MongoManager = MongoManager;
374
- var MongoManagerModel = /** @class */ (function () {
375
- function MongoManagerModel(options) {
376
- this.collection_main = null;
377
- this.collection_version = null;
378
- if (options.collectionName === 'users') {
379
- this.collection_main = new MongoManagerUserCollection(options);
380
- }
381
- else {
382
- this.collection_main = new MongoManagerCollection(options);
383
- }
384
- if (options.useVersionCollection) {
385
- this.collection_main.useVersions = true;
386
- var versionSchema = (0, common_1.deepCopy)(options.schema);
387
- versionSchema._id.type = 'Object';
388
- versionSchema._id.blackbox = true;
389
- var versionOptions = {
390
- collectionName: options.collectionName + '.versions',
391
- schema: versionSchema,
392
- useVersionCollection: false,
393
- useReportBuilder: false,
394
- reportBuilderLookupTables: [],
395
- timestamps: true,
396
- createLogs: false,
397
- checkSchema: false,
398
- collectionOptions: null
399
- };
400
- if (options.collectionName === 'users') {
401
- this.collection_version = new MongoManagerUserCollection(versionOptions);
402
- }
403
- else {
404
- this.collection_version = new MongoManagerCollection(versionOptions);
405
- }
406
- this.collection_version.createIndex({ '_id._id': 1, '_id.__v': 1 });
407
- this.collection_main.versionCollection = options.collectionName + '.versions';
408
- }
409
- }
410
- return MongoManagerModel;
411
- }());
412
- exports.MongoManagerModel = MongoManagerModel;
413
- var MongoManagerCollection = /** @class */ (function () {
414
- function MongoManagerCollection(options) {
415
- var _this = this;
416
- this.collectionName = '';
417
- this.checkSchema = false;
418
- this.simplschema = null;
419
- this.rbSchema = null;
420
- this.timestamps = false;
421
- this.useVersions = false;
422
- this.versionCollection = '';
423
- this.createLogs = true;
424
- this.useRB = false;
425
- this.collectionName = options.collectionName;
426
- this.simplschema = new simpl_schema_1.default(options.schema);
427
- this.timestamps = options.timestamps;
428
- this.createLogs = options.createLogs;
429
- this.checkSchema = options.checkSchema;
430
- this.collectionOptions = options.collectionOptions;
431
- if (options.useReportBuilder) {
432
- this.useRB = true;
433
- var schemaCopy = (0, common_1.deepCopy)(options.schema);
434
- var rbSchema = (0, common_1.buildRbLookups)(options.reportBuilderLookupTables, schemaCopy, []);
435
- this.rbSchema = (0, common_1.buildRbSchema)(rbSchema);
436
- }
437
- var interval = setInterval(function () {
438
- if (index_1.ResolveIOServer && index_1.ResolveIOServer.getMainServer() && index_1.ResolveIOServer.getMongoManager() && index_1.ResolveIOServer.getMongoManager().getServerCollections().length) {
439
- index_1.ResolveIOServer.getMongoManager().registerCollection(_this);
440
- clearInterval(interval);
441
- }
442
- }, 1);
443
- }
444
- // Method to extract index name from error message
445
- MongoManagerCollection.prototype.extractIndexNameFromError = function (errorMessage) {
446
- var regexPattern = /Index already exists with a different name: (\S+)/;
447
- var matches = errorMessage.match(regexPattern);
448
- if (!matches || matches.length <= 1) {
449
- // If the first pattern doesn't match, try the second pattern
450
- regexPattern = /existing index:.*name: "([^"]+)"/;
451
- matches = errorMessage.match(regexPattern);
452
- }
453
- return matches && matches.length > 1 ? matches[1] : null;
454
- };
455
- MongoManagerCollection.prototype.aggregate = function (pipeline, options, skipCache) {
456
- var _this = this;
457
- if (skipCache === void 0) { skipCache = false; }
458
- return new Promise(function (resolve, reject) {
459
- // if (!skipCache) {
460
- // ResolveIOServer.getMongoManager().addToQueue({
461
- // _id: 0,
462
- // name_collection: this.collectionName,
463
- // name_function: 'aggregate',
464
- // name_function_addt: 'toArray',
465
- // data_function: [pipeline, options],
466
- // data_function_addt: [],
467
- // cbs: [(err, res, cached) => {
468
- // if (err) {
469
- // reject(err);
470
- // }
471
- // else {
472
- // resolve(res);
473
- // }
474
- // }],
475
- // cbs_next: [],
476
- // running: false,
477
- // cacheId: 0,
478
- // lookup_collections: pipeline.filter(a => a['$lookup'] && a['$lookup'].from).map(a => a['$lookup'].from).filter((elem, index, self) => {
479
- // return index === self.indexOf(elem);
480
- // }),
481
- // invalidateFlag: false,
482
- // invalidateCount: 0
483
- // });
484
- // }
485
- // else {
486
- // let monitor = new MonitorMongo('aggregate', this.collectionName, JSON.stringify([pipeline, options]));
487
- // ResolveIOServer.getMainDB().collection<T>(this.collectionName, this.collectionOptions).aggregate(pipeline, options).toArray().then(res => {
488
- // monitor.finish();
489
- // resolve(res);
490
- // }, err => {
491
- // monitor.finish();
492
- // console.log(new Date(), 'Error Aggregate', this.collectionName, pipeline, options, err);
493
- // reject(err);
494
- // });
495
- // }
496
- var monitor = new monitor_manager_1.MonitorMongo('aggregate', _this.collectionName, JSON.stringify([pipeline, options]));
497
- index_1.ResolveIOServer.getMainDB().collection(_this.collectionName, _this.collectionOptions).aggregate(pipeline, options).toArray().then(function (res) {
498
- monitor.finish();
499
- resolve(res);
500
- }, function (err) {
501
- monitor.finish();
502
- console.log(new Date(), 'Error Aggregate', _this.collectionName, pipeline, options, err);
503
- reject(err);
504
- });
505
- });
506
- };
507
- MongoManagerCollection.prototype.aggregateCount = function (pipeline, options) {
508
- var _this = this;
509
- return new Promise(function (resolve, reject) {
510
- index_1.ResolveIOServer.getMongoManager().addToQueue({
511
- _id: 0,
512
- name_collection: _this.collectionName,
513
- name_function: 'aggregate',
514
- name_function_addt: 'count',
515
- data_function: [pipeline, options],
516
- data_function_addt: [],
517
- cbs: [function (err, res, cached) {
518
- if (err) {
519
- reject(err);
520
- }
521
- else {
522
- resolve(res);
523
- }
524
- }],
525
- cbs_next: [],
526
- running: false,
527
- cacheId: 0,
528
- lookup_collections: pipeline.filter(function (a) { return a['$lookup'] && a['$lookup'].from; }).map(function (a) { return a['$lookup'].from; }).filter(function (elem, index, self) {
529
- return index === self.indexOf(elem);
530
- }),
531
- invalidateFlag: false,
532
- invalidateCount: 0
533
- });
534
- });
535
- };
536
- MongoManagerCollection.prototype.aggregateCursor = function (pipeline, options) {
537
- var monitor = new monitor_manager_1.MonitorMongo('aggregateCursor', this.collectionName, JSON.stringify([pipeline, options]));
538
- var cursor = index_1.ResolveIOServer.getMainDB().collection(this.collectionName, this.collectionOptions).aggregate(pipeline, options);
539
- cursor.on('close', function (ev) {
540
- monitor.finish();
541
- return ev;
542
- });
543
- return cursor;
544
- };
545
- MongoManagerCollection.prototype.aggregateStream = function (pipeline, options, streamOptions) {
546
- var monitor = new monitor_manager_1.MonitorMongo('aggregateStream', this.collectionName, JSON.stringify([pipeline, options, streamOptions]));
547
- var stream = index_1.ResolveIOServer.getMainDB().collection(this.collectionName, this.collectionOptions).aggregate(pipeline, options).stream(streamOptions);
548
- stream.on('end', function (ev) {
549
- monitor.finish();
550
- return ev;
551
- })
552
- .on('error', function (ev) {
553
- monitor.finish();
554
- return ev;
555
- })
556
- .on('close', function (ev) {
557
- monitor.finish();
558
- return ev;
559
- });
560
- return stream;
561
- };
562
- // bulkWrite(operations: AnyBulkWriteOperation<T>[], options: BulkWriteOptions): Promise<BulkWriteResult> {
563
- MongoManagerCollection.prototype.bulkWrite = function (operations, options) {
564
- var _this = this;
565
- return new Promise(function (resolve, reject) {
566
- var monitor = new monitor_manager_1.MonitorMongo('bulkWrite', _this.collectionName, JSON.stringify([operations.slice(-100), options]));
567
- index_1.ResolveIOServer.getMainDB().collection(_this.collectionName, _this.collectionOptions).bulkWrite(operations, options).then(function (res) {
568
- monitor.finish();
569
- resolve(res);
570
- }, function (err) {
571
- monitor.finish();
572
- console.log(new Date(), 'Error Bulk Write', _this.collectionName, operations.slice(-100), options, err);
573
- reject(err);
574
- });
575
- });
576
- };
577
- MongoManagerCollection.prototype.countDocuments = function (filter, options) {
578
- var _this = this;
579
- if (filter === void 0) { filter = {}; }
580
- return new Promise(function (resolve, reject) {
581
- var monitor = new monitor_manager_1.MonitorMongo('countDocuments', _this.collectionName, JSON.stringify([filter, options]));
582
- index_1.ResolveIOServer.getMainDB().collection(_this.collectionName, _this.collectionOptions).countDocuments(filter, options).then(function (res) {
583
- monitor.finish();
584
- resolve(res);
585
- }, function (err) {
586
- monitor.finish();
587
- console.log(new Date(), 'Error Count Documents', _this.collectionName, filter, options, err);
588
- reject(err);
589
- });
590
- });
591
- };
592
- //Helper Function (1 or Many) - Not Real Mongo Function
593
- MongoManagerCollection.prototype.create = function (f_docs, options) {
594
- if (!Array.isArray(f_docs)) {
595
- return this.insertOne(f_docs, options);
596
- }
597
- else if (f_docs.length === 1) {
598
- return this.insertOne(f_docs[0], options);
599
- }
600
- return this.insertMany(f_docs, options);
601
- };
602
- MongoManagerCollection.prototype.createIndex = function (fieldOrSpec, options) {
603
- var _this = this;
604
- return new Promise(function (resolve, reject) {
605
- MongoManagerCollection.indexQueue.push({
606
- action: 'createIndex',
607
- collection: _this,
608
- specs: [fieldOrSpec],
609
- options: options
610
- }, function (err, result) {
611
- if (err)
612
- reject(err);
613
- else
614
- resolve(result);
615
- });
616
- });
617
- };
618
- MongoManagerCollection.prototype.createIndexes = function (indexSpecs, options) {
619
- var _this = this;
620
- return new Promise(function (resolve, reject) {
621
- MongoManagerCollection.indexQueue.push({
622
- action: 'createIndexes',
623
- collection: _this,
624
- specs: [indexSpecs],
625
- options: options
626
- }, function (err, result) {
627
- if (err)
628
- reject(err);
629
- else
630
- resolve(result);
631
- });
632
- });
633
- };
634
- MongoManagerCollection.prototype.deleteMany = function (filter, options, bypassLogs) {
635
- var _this = this;
636
- if (filter === void 0) { filter = {}; }
637
- if (bypassLogs === void 0) { bypassLogs = false; }
638
- return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
639
- var docs, i, doc, versionDoc, monitor;
640
- var _this = this;
641
- return __generator(this, function (_b) {
642
- switch (_b.label) {
643
- case 0:
644
- if (!(this.createLogs && !bypassLogs)) return [3 /*break*/, 2];
645
- return [4 /*yield*/, this.find(filter)];
646
- case 1:
647
- docs = _b.sent();
648
- for (i = 0; i < docs.length; i++) {
649
- doc = docs[i];
650
- log_collection_1.Logs.insertOne({
651
- _id: objectIdHexString(),
652
- type: 'document',
653
- collection: this.collectionName,
654
- id_document: doc._id,
655
- payload: (0, common_1.getBinarySize)(JSON.stringify([doc, filter, options])) < 200000 ? JSON.stringify([doc, filter, options], null, 2) : 'Too Big',
656
- method: 'deleteMany',
657
- id_user: '',
658
- user: '',
659
- messageId: 0,
660
- route: ''
661
- });
662
- if (this.useVersions) {
663
- versionDoc = (0, common_1.deepCopy)(doc);
664
- versionDoc._id = { _id: doc._id, __v: doc.__v };
665
- index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).replaceOne({ _id: { _id: doc._id, __v: doc.__v } }, versionDoc, { upsert: true });
666
- index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).deleteMany({ $and: [{ '_id._id': doc._id }, { '_id.__v': { $lt: doc.__v - 1 } }] });
667
- }
668
- }
669
- _b.label = 2;
670
- case 2:
671
- monitor = new monitor_manager_1.MonitorMongo('deleteMany', this.collectionName, JSON.stringify([filter, options]));
672
- index_1.ResolveIOServer.getMainDB().collection(this.collectionName, this.collectionOptions).deleteMany(filter, options).then(function (res) {
673
- monitor.finish();
674
- if (res.acknowledged) {
675
- index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(_this.collectionName);
676
- resolve(res.deletedCount);
677
- }
678
- else {
679
- reject(res.acknowledged);
680
- }
681
- }, function (err) {
682
- monitor.finish();
683
- console.log(new Date(), 'Error Delete Many', _this.collectionName, filter, options, err);
684
- reject(err);
685
- });
686
- return [2 /*return*/];
687
- }
688
- });
689
- }); });
690
- };
691
- MongoManagerCollection.prototype.deleteOne = function (filter, options, bypassLogs) {
692
- var _this = this;
693
- if (filter === void 0) { filter = {}; }
694
- if (bypassLogs === void 0) { bypassLogs = false; }
695
- return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
696
- var monitor_3, monitor_4;
697
- var _this = this;
698
- return __generator(this, function (_b) {
699
- if (this.createLogs && !bypassLogs) {
700
- monitor_3 = new monitor_manager_1.MonitorMongo('findOneAndDelete', this.collectionName, JSON.stringify([filter, options]));
701
- index_1.ResolveIOServer.getMainDB().collection(this.collectionName, this.collectionOptions).findOneAndDelete(filter, options).then(function (returnVal) { return __awaiter(_this, void 0, void 0, function () {
702
- var doc, versionDoc;
703
- return __generator(this, function (_b) {
704
- monitor_3.finish();
705
- doc = returnVal;
706
- if (doc) {
707
- if (this.createLogs && !bypassLogs) {
708
- log_collection_1.Logs.insertOne({
709
- _id: objectIdHexString(),
710
- type: 'document',
711
- collection: this.collectionName,
712
- id_document: doc._id,
713
- payload: (0, common_1.getBinarySize)(JSON.stringify([doc, filter, options])) < 200000 ? JSON.stringify([doc, filter, options], null, 2) : 'Too Big',
714
- method: 'deleteOne',
715
- id_user: '',
716
- user: '',
717
- messageId: 0,
718
- route: ''
719
- });
720
- }
721
- if (this.useVersions) {
722
- versionDoc = (0, common_1.deepCopy)(doc);
723
- versionDoc._id = { _id: doc._id, __v: doc.__v };
724
- index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).replaceOne({ _id: { _id: doc._id, __v: doc.__v } }, versionDoc, { upsert: true });
725
- index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).deleteMany({ $and: [{ '_id._id': doc._id }, { '_id.__v': { $lt: doc.__v - 1 } }] });
726
- }
727
- index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(this.collectionName);
728
- resolve(1);
729
- }
730
- else {
731
- resolve(0);
732
- }
733
- return [2 /*return*/];
734
- });
735
- }); }, function (err) {
736
- monitor_3.finish();
737
- console.log(new Date(), 'Error Find One And Delete', _this.collectionName, filter, options, err);
738
- reject(err);
739
- });
740
- }
741
- else {
742
- monitor_4 = new monitor_manager_1.MonitorMongo('deleteOne', this.collectionName, JSON.stringify([filter, options]));
743
- index_1.ResolveIOServer.getMainDB().collection(this.collectionName, this.collectionOptions).deleteOne(filter, options).then(function (res) {
744
- monitor_4.finish();
745
- if (res.acknowledged) {
746
- index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(_this.collectionName);
747
- resolve(res.deletedCount);
748
- }
749
- else {
750
- reject(res.acknowledged);
751
- }
752
- }, function (err) {
753
- monitor_4.finish();
754
- console.log(new Date(), 'Error Delete One', _this.collectionName, filter, options, err);
755
- reject(err);
756
- });
757
- }
758
- return [2 /*return*/];
759
- });
760
- }); });
761
- };
762
- MongoManagerCollection.prototype.distinct = function (key, filter, options) {
763
- var _this = this;
764
- return new Promise(function (resolve, reject) {
765
- var monitor = new monitor_manager_1.MonitorMongo('distinct', _this.collectionName, JSON.stringify([key, filter, options]));
766
- index_1.ResolveIOServer.getMainDB().collection(_this.collectionName, _this.collectionOptions).distinct(key, filter, options).then(function (res) {
767
- monitor.finish();
768
- resolve(res);
769
- }, function (err) {
770
- monitor.finish();
771
- console.log(new Date(), 'Error Distinct', _this.collectionName, filter, options, err);
772
- reject(err);
773
- });
774
- });
775
- };
776
- MongoManagerCollection.prototype.drop = function (options) {
777
- var _this = this;
778
- return new Promise(function (resolve, reject) {
779
- var monitor = new monitor_manager_1.MonitorMongo('drop', _this.collectionName, JSON.stringify([options]));
780
- index_1.ResolveIOServer.getMainDB().collection(_this.collectionName, _this.collectionOptions).drop(options).then(function (res) {
781
- monitor.finish();
782
- resolve(res);
783
- }, function (err) {
784
- monitor.finish();
785
- console.log(new Date(), 'Error Count Documents', _this.collectionName, options, err);
786
- reject(err);
787
- });
788
- });
789
- };
790
- MongoManagerCollection.prototype.dropIndex = function (indexName, options) {
791
- var _this = this;
792
- return new Promise(function (resolve, reject) {
793
- var monitor = new monitor_manager_1.MonitorMongo('dropIndex', _this.collectionName, JSON.stringify([indexName, options]));
794
- index_1.ResolveIOServer.getMainDB().collection(_this.collectionName, _this.collectionOptions).dropIndex(indexName, options).then(function (res) {
795
- monitor.finish();
796
- resolve(res);
797
- }, function (err) {
798
- monitor.finish();
799
- console.log(new Date(), 'Error Drop Index', _this.collectionName, indexName, options, err);
800
- reject(err);
801
- });
802
- });
803
- };
804
- MongoManagerCollection.prototype.dropIndexes = function (options) {
805
- var _this = this;
806
- return new Promise(function (resolve, reject) {
807
- var monitor = new monitor_manager_1.MonitorMongo('dropIndexes', _this.collectionName, JSON.stringify([options]));
808
- index_1.ResolveIOServer.getMainDB().collection(_this.collectionName, _this.collectionOptions).dropIndexes(options).then(function (res) {
809
- monitor.finish();
810
- resolve(res);
811
- }, function (err) {
812
- monitor.finish();
813
- console.log(new Date(), 'Error Drop Indexes', _this.collectionName, options, err);
814
- reject(err);
815
- });
816
- });
817
- };
818
- MongoManagerCollection.prototype.find = function (filter, options, skipCache) {
819
- var _this = this;
820
- if (filter === void 0) { filter = {}; }
821
- if (skipCache === void 0) { skipCache = false; }
822
- return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
823
- var monitor_5;
824
- var _this = this;
825
- return __generator(this, function (_b) {
826
- if (!skipCache) {
827
- index_1.ResolveIOServer.getMongoManager().addToQueue({
828
- _id: 0,
829
- name_collection: this.collectionName,
830
- name_function: 'find',
831
- name_function_addt: 'toArray',
832
- data_function: [filter, options],
833
- data_function_addt: [],
834
- cbs: [function (err, res, cached) {
835
- if (err) {
836
- reject(err);
837
- }
838
- else {
839
- resolve(res);
840
- }
841
- }],
842
- cbs_next: [],
843
- running: false,
844
- cacheId: 0,
845
- lookup_collections: [],
846
- invalidateFlag: false,
847
- invalidateCount: 0
848
- });
849
- }
850
- else {
851
- monitor_5 = new monitor_manager_1.MonitorMongo('find', this.collectionName, JSON.stringify([filter, options]));
852
- index_1.ResolveIOServer.getMainDB().collection(this.collectionName, this.collectionOptions).find(filter, options).toArray().then(function (res) {
853
- monitor_5.finish();
854
- resolve(res);
855
- }, function (err) {
856
- monitor_5.finish();
857
- console.log(new Date(), 'Error Find', _this.collectionName, filter, options, err);
858
- reject(err);
859
- });
860
- }
861
- return [2 /*return*/];
862
- });
863
- }); });
864
- };
865
- MongoManagerCollection.prototype.findById = function (id, options) {
866
- var _this = this;
867
- return new Promise(function (resolve, reject) {
868
- var monitor = new monitor_manager_1.MonitorMongo('findById', _this.collectionName, JSON.stringify([{ _id: id }, options]));
869
- index_1.ResolveIOServer.getMainDB().collection(_this.collectionName, _this.collectionOptions).findOne({ _id: id }, options).then(function (res) {
870
- monitor.finish();
871
- resolve(res);
872
- }, function (err) {
873
- monitor.finish();
874
- console.log(new Date(), 'Error Find By Id', _this.collectionName, { _id: id }, options, err);
875
- reject(err);
876
- });
877
- });
878
- };
879
- MongoManagerCollection.prototype.findCount = function (filter, options) {
880
- var _this = this;
881
- if (filter === void 0) { filter = {}; }
882
- return new Promise(function (resolve, reject) {
883
- var monitor = new monitor_manager_1.MonitorMongo('findCount', _this.collectionName, JSON.stringify([filter, options]));
884
- index_1.ResolveIOServer.getMainDB().collection(_this.collectionName, _this.collectionOptions).find(filter, options).count().then(function (res) {
885
- monitor.finish();
886
- resolve(res);
887
- }, function (err) {
888
- monitor.finish();
889
- console.log(new Date(), 'Error Find Count', _this.collectionName, filter, options, err);
890
- reject(err);
891
- });
892
- });
893
- };
894
- MongoManagerCollection.prototype.findCursor = function (filter, options) {
895
- if (filter === void 0) { filter = {}; }
896
- var monitor = new monitor_manager_1.MonitorMongo('findCursor', this.collectionName, JSON.stringify([filter, options]));
897
- var cursor = index_1.ResolveIOServer.getMainDB().collection(this.collectionName, this.collectionOptions).find(filter, options);
898
- cursor.on('close', function (ev) {
899
- monitor.finish();
900
- cursor.removeAllListeners();
901
- return ev;
902
- });
903
- return cursor;
904
- };
905
- MongoManagerCollection.prototype.findStream = function (filter, options, streamOptions) {
906
- if (filter === void 0) { filter = {}; }
907
- var monitor = new monitor_manager_1.MonitorMongo('findStream', this.collectionName, JSON.stringify([filter, options, streamOptions]));
908
- var stream = index_1.ResolveIOServer.getMainDB().collection(this.collectionName, this.collectionOptions).find(filter, options).stream(streamOptions);
909
- stream.on('end', function (ev) {
910
- monitor.finish();
911
- return ev;
912
- })
913
- .on('error', function (ev) {
914
- monitor.finish();
915
- return ev;
916
- })
917
- .on('close', function (ev) {
918
- monitor.finish();
919
- return ev;
920
- });
921
- return stream;
922
- };
923
- MongoManagerCollection.prototype.findOne = function (filter, options, skipCache) {
924
- var _this = this;
925
- if (filter === void 0) { filter = {}; }
926
- if (skipCache === void 0) { skipCache = false; }
927
- return new Promise(function (resolve, reject) {
928
- if (!skipCache) {
929
- index_1.ResolveIOServer.getMongoManager().addToQueue({
930
- _id: 0,
931
- name_collection: _this.collectionName,
932
- name_function: 'findOne',
933
- name_function_addt: '',
934
- data_function: [filter, options],
935
- data_function_addt: [],
936
- cbs: [function (err, res, cached) {
937
- if (err) {
938
- reject(err);
939
- }
940
- else {
941
- resolve(res);
942
- }
943
- }],
944
- cbs_next: [],
945
- running: false,
946
- cacheId: 0,
947
- lookup_collections: [],
948
- invalidateFlag: false,
949
- invalidateCount: 0
950
- });
951
- }
952
- else {
953
- var monitor_6 = new monitor_manager_1.MonitorMongo('findOne', _this.collectionName, JSON.stringify([filter, options]));
954
- index_1.ResolveIOServer.getMainDB().collection(_this.collectionName, _this.collectionOptions).findOne(filter, options).then(function (res) {
955
- monitor_6.finish();
956
- resolve(res);
957
- }, function (err) {
958
- monitor_6.finish();
959
- console.log(new Date(), 'Error Find One', _this.collectionName, filter, options, err);
960
- reject(err);
961
- });
962
- }
963
- });
964
- };
965
- MongoManagerCollection.prototype.findOneAndDelete = function (filter, options, bypassLogs) {
966
- var _this = this;
967
- if (filter === void 0) { filter = {}; }
968
- if (bypassLogs === void 0) { bypassLogs = false; }
969
- return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
970
- var monitor;
971
- var _this = this;
972
- return __generator(this, function (_b) {
973
- monitor = new monitor_manager_1.MonitorMongo('findOneAndDelete', this.collectionName, JSON.stringify([filter, options]));
974
- index_1.ResolveIOServer.getMainDB().collection(this.collectionName, this.collectionOptions).findOneAndDelete(filter, options).then(function (res) {
975
- monitor.finish();
976
- var doc = res;
977
- if (doc) {
978
- if (_this.createLogs && !bypassLogs) {
979
- log_collection_1.Logs.insertOne({
980
- _id: objectIdHexString(),
981
- type: 'document',
982
- collection: _this.collectionName,
983
- id_document: doc._id,
984
- payload: (0, common_1.getBinarySize)(JSON.stringify([doc, filter, options])) < 200000 ? JSON.stringify([doc, filter, options], null, 2) : 'Too Big',
985
- method: 'findOneAndDelete',
986
- id_user: '',
987
- user: '',
988
- messageId: 0,
989
- route: ''
990
- });
991
- }
992
- if (_this.useVersions) {
993
- var versionDoc = (0, common_1.deepCopy)(doc);
994
- versionDoc._id = { _id: doc._id, __v: doc.__v };
995
- index_1.ResolveIOServer.getMongoManager().collection(_this.versionCollection).replaceOne({ _id: { _id: doc._id, __v: doc.__v } }, versionDoc, { upsert: true });
996
- }
997
- index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(_this.collectionName);
998
- resolve(doc);
999
- }
1000
- else {
1001
- resolve(null);
1002
- }
1003
- }, function (err) {
1004
- monitor.finish();
1005
- console.log(new Date(), 'Error Find One And Delete', _this.collectionName, filter, options, err);
1006
- reject(err);
1007
- });
1008
- return [2 /*return*/];
1009
- });
1010
- }); });
1011
- };
1012
- MongoManagerCollection.prototype.findOneAndReplace = function (filter, replacement, options, bypassLogs, bypassCheckSchema) {
1013
- var _this = this;
1014
- if (filter === void 0) { filter = {}; }
1015
- if (bypassLogs === void 0) { bypassLogs = false; }
1016
- if (bypassCheckSchema === void 0) { bypassCheckSchema = false; }
1017
- return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
1018
- var validation, isValid, date, monitor;
1019
- var _this = this;
1020
- return __generator(this, function (_b) {
1021
- if (this.checkSchema && !bypassCheckSchema) {
1022
- validation = this.simplschema.newContext();
1023
- isValid = validation.validate(replacement);
1024
- if (!isValid) {
1025
- console.log(new Date(), this.collectionName, 'Schema Errors - findOneAndReplace', validation.validationErrors());
1026
- index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal.call(index_1.ResolveIOServer.getMainServer().getMethodManager(), 'insertErrorLog', 'Schema Failed on findOneAndReplace - ' + this.collectionName, [validation.validationErrors(), replacement]);
1027
- reject(validation.validationErrors());
1028
- return [2 /*return*/];
1029
- }
1030
- }
1031
- date = new Date();
1032
- if (this.timestamps) {
1033
- replacement.updatedAt = date;
1034
- }
1035
- if (options && options.upsert) {
1036
- if (!replacement._id) {
1037
- replacement._id = objectIdHexString();
1038
- }
1039
- if (this.useVersions) {
1040
- replacement.__v = 0;
1041
- }
1042
- if (this.timestamps && !replacement.createdAt) {
1043
- replacement.createdAt = date;
1044
- }
1045
- }
1046
- monitor = new monitor_manager_1.MonitorMongo('findOneAndReplace', this.collectionName, JSON.stringify([filter, replacement, options]));
1047
- index_1.ResolveIOServer.getMainDB().collection(this.collectionName, this.collectionOptions).findOneAndReplace(filter, replacement, options).then(function (res) {
1048
- monitor.finish();
1049
- var doc = res;
1050
- if (doc) {
1051
- if (_this.createLogs && !bypassLogs) {
1052
- log_collection_1.Logs.insertOne({
1053
- _id: objectIdHexString(),
1054
- type: 'document',
1055
- collection: _this.collectionName,
1056
- id_document: doc._id,
1057
- payload: (0, common_1.getBinarySize)(JSON.stringify([doc, filter, replacement, options])) < 200000 ? JSON.stringify([doc, filter, replacement, options], null, 2) : 'Too Big',
1058
- method: 'findOneAndReplace',
1059
- id_user: '',
1060
- user: '',
1061
- messageId: 0,
1062
- route: ''
1063
- });
1064
- }
1065
- if (_this.useVersions) {
1066
- var versionDoc = (0, common_1.deepCopy)(doc);
1067
- versionDoc._id = { _id: doc._id, __v: doc.__v };
1068
- index_1.ResolveIOServer.getMongoManager().collection(_this.versionCollection).replaceOne({ _id: { _id: doc._id, __v: doc.__v } }, versionDoc, { upsert: true });
1069
- }
1070
- index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(_this.collectionName);
1071
- resolve(doc);
1072
- }
1073
- else {
1074
- resolve(null);
1075
- }
1076
- }, function (err) {
1077
- monitor.finish();
1078
- console.log(new Date(), 'Error Find One And Replace', _this.collectionName, filter, options, err);
1079
- reject(err);
1080
- });
1081
- return [2 /*return*/];
1082
- });
1083
- }); });
1084
- };
1085
- MongoManagerCollection.prototype.findOneAndUpdate = function (filter, update, options, bypassLogs, bypassCheckSchema) {
1086
- var _this = this;
1087
- if (filter === void 0) { filter = {}; }
1088
- if (bypassLogs === void 0) { bypassLogs = false; }
1089
- if (bypassCheckSchema === void 0) { bypassCheckSchema = false; }
1090
- return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
1091
- var validation, isValid, date, monitor;
1092
- var _this = this;
1093
- return __generator(this, function (_b) {
1094
- if (this.checkSchema && !bypassCheckSchema) {
1095
- validation = this.simplschema.newContext();
1096
- isValid = validation.validate(update, { modifier: true });
1097
- if (!isValid) {
1098
- console.log(new Date(), this.collectionName, 'Schema Errors - findOneAndUpdate', validation.validationErrors());
1099
- index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal.call(index_1.ResolveIOServer.getMainServer().getMethodManager(), 'insertErrorLog', 'Schema Failed on findOneAndUpdate - ' + this.collectionName, [validation.validationErrors(), update]);
1100
- reject(validation.validationErrors());
1101
- return [2 /*return*/];
1102
- }
1103
- }
1104
- if (this.timestamps) {
1105
- date = new Date();
1106
- if (!update.$set) {
1107
- update.$set = { updatedAt: date };
1108
- }
1109
- else {
1110
- update.$set.updatedAt = date;
1111
- }
1112
- }
1113
- if (options && options.upsert) {
1114
- if (!update.$setOnInsert) {
1115
- if (this.timestamps) {
1116
- update.$setOnInsert = {
1117
- _id: objectIdHexString(),
1118
- createdAt: new Date()
1119
- };
1120
- }
1121
- else {
1122
- update.$setOnInsert = {
1123
- _id: objectIdHexString()
1124
- };
1125
- }
1126
- }
1127
- else {
1128
- if (!update.$setOnInsert._id) {
1129
- update.$setOnInsert._id = objectIdHexString();
1130
- }
1131
- if (this.timestamps) {
1132
- update.$setOnInsert.createdAt = new Date();
1133
- }
1134
- }
1135
- }
1136
- monitor = new monitor_manager_1.MonitorMongo('findOneAndUpdate', this.collectionName, JSON.stringify([filter, update, options]));
1137
- index_1.ResolveIOServer.getMainDB().collection(this.collectionName, this.collectionOptions).findOneAndUpdate(filter, update, options).then(function (res) {
1138
- monitor.finish();
1139
- var doc = res;
1140
- if (doc) {
1141
- if (_this.createLogs && !bypassLogs) {
1142
- log_collection_1.Logs.insertOne({
1143
- _id: objectIdHexString(),
1144
- type: 'document',
1145
- collection: _this.collectionName,
1146
- id_document: doc._id,
1147
- payload: (0, common_1.getBinarySize)(JSON.stringify([doc, filter, update, options])) < 200000 ? JSON.stringify([doc, filter, update, options], null, 2) : 'Too Big',
1148
- method: 'findOneAndUpdate',
1149
- id_user: '',
1150
- user: '',
1151
- messageId: 0,
1152
- route: ''
1153
- });
1154
- }
1155
- if (_this.useVersions) {
1156
- var versionDoc = (0, common_1.deepCopy)(doc);
1157
- versionDoc._id = { _id: doc._id, __v: doc.__v };
1158
- index_1.ResolveIOServer.getMongoManager().collection(_this.versionCollection).replaceOne({ _id: { _id: doc._id, __v: doc.__v } }, versionDoc, { upsert: true });
1159
- }
1160
- index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(_this.collectionName);
1161
- resolve(doc);
1162
- }
1163
- else {
1164
- resolve(null);
1165
- }
1166
- }, function (err) {
1167
- monitor.finish();
1168
- console.log(new Date(), 'Error Find One And Update', _this.collectionName, filter, options, err);
1169
- reject(err);
1170
- });
1171
- return [2 /*return*/];
1172
- });
1173
- }); });
1174
- };
1175
- MongoManagerCollection.prototype.indexes = function (options) {
1176
- var _this = this;
1177
- return new Promise(function (resolve, reject) {
1178
- var monitor = new monitor_manager_1.MonitorMongo('indexes', _this.collectionName, JSON.stringify([options]));
1179
- index_1.ResolveIOServer.getMainDB().collection(_this.collectionName, _this.collectionOptions).indexes(options).then(function (res) {
1180
- monitor.finish();
1181
- resolve(res);
1182
- }, function (err) {
1183
- monitor.finish();
1184
- console.log(new Date(), 'Error Indexes', _this.collectionName, options, err);
1185
- reject(err);
1186
- });
1187
- });
1188
- };
1189
- MongoManagerCollection.prototype.indexExists = function (indexes, options) {
1190
- var _this = this;
1191
- return new Promise(function (resolve, reject) {
1192
- var monitor = new monitor_manager_1.MonitorMongo('indexExists', _this.collectionName, JSON.stringify([indexes, options]));
1193
- index_1.ResolveIOServer.getMainDB().collection(_this.collectionName, _this.collectionOptions).indexExists(indexes, options).then(function (res) {
1194
- monitor.finish();
1195
- resolve(res);
1196
- }, function (err) {
1197
- monitor.finish();
1198
- console.log(new Date(), 'Error Index Exists', _this.collectionName, indexes, options, err);
1199
- reject(err);
1200
- });
1201
- });
1202
- };
1203
- MongoManagerCollection.prototype.insertMany = function (docs, options, bypassLogs, bypassCheckSchema, bypassMonitor) {
1204
- var _this = this;
1205
- if (bypassLogs === void 0) { bypassLogs = false; }
1206
- if (bypassCheckSchema === void 0) { bypassCheckSchema = false; }
1207
- if (bypassMonitor === void 0) { bypassMonitor = false; }
1208
- return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
1209
- var validationResults, validDocs, i, doc, date, monitor_7;
1210
- var _this = this;
1211
- return __generator(this, function (_b) {
1212
- if (!docs.length) {
1213
- resolve([]);
1214
- return [2 /*return*/];
1215
- }
1216
- validationResults = [];
1217
- if (this.checkSchema && !bypassCheckSchema) {
1218
- docs.forEach(function (doc) {
1219
- var validation = _this.simplschema.newContext();
1220
- var isValid = validation.validate(doc);
1221
- if (!isValid) {
1222
- console.log(new Date(), _this.collectionName, 'Schema Errors - insertMany', validation.validationErrors());
1223
- index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal.call(index_1.ResolveIOServer.getMainServer().getMethodManager(), 'insertErrorLog', 'Schema Failed on insertMany - ' + _this.collectionName, [validation.validationErrors(), doc]);
1224
- validationResults.push(false);
1225
- }
1226
- else {
1227
- validationResults.push(true);
1228
- }
1229
- });
1230
- }
1231
- validDocs = this.checkSchema ? docs.filter(function (a, idx) { return validationResults[idx]; }) : docs;
1232
- for (i = 0; i < validDocs.length; i++) {
1233
- doc = validDocs[i];
1234
- if (!doc._id) {
1235
- doc._id = objectIdHexString();
1236
- }
1237
- if (this.timestamps) {
1238
- date = new Date();
1239
- doc.createdAt = date;
1240
- doc.updatedAt = date;
1241
- }
1242
- if (this.createLogs && !bypassLogs) {
1243
- log_collection_1.Logs.insertOne({
1244
- _id: objectIdHexString(),
1245
- type: 'document',
1246
- collection: this.collectionName,
1247
- id_document: doc._id,
1248
- payload: (0, common_1.getBinarySize)(JSON.stringify([doc, options])) < 200000 ? JSON.stringify([doc, options], null, 2) : 'Too Big',
1249
- method: 'insertMany',
1250
- id_user: '',
1251
- user: '',
1252
- messageId: 0,
1253
- route: ''
1254
- });
1255
- }
1256
- }
1257
- if (validDocs.length) {
1258
- monitor_7 = null;
1259
- if (!bypassMonitor) {
1260
- monitor_7 = new monitor_manager_1.MonitorMongo('insertMany', this.collectionName, JSON.stringify([validDocs, options]));
1261
- }
1262
- index_1.ResolveIOServer.getMainDB().collection(this.collectionName, this.collectionOptions).insertMany(validDocs, options).then(function (res) {
1263
- if (monitor_7) {
1264
- monitor_7.finish();
1265
- }
1266
- if (res.acknowledged) {
1267
- index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(_this.collectionName);
1268
- resolve(validDocs);
1269
- }
1270
- else {
1271
- reject(res.acknowledged);
1272
- }
1273
- }, function (err) {
1274
- if (monitor_7) {
1275
- monitor_7.finish();
1276
- }
1277
- console.log(new Date(), 'Error Insert Many', _this.collectionName, validDocs, options, err);
1278
- reject(err);
1279
- });
1280
- }
1281
- return [2 /*return*/];
1282
- });
1283
- }); });
1284
- };
1285
- MongoManagerCollection.prototype.insertOne = function (doc, options, bypassLogs, bypassCheckSchema) {
1286
- var _this = this;
1287
- if (bypassLogs === void 0) { bypassLogs = false; }
1288
- if (bypassCheckSchema === void 0) { bypassCheckSchema = false; }
1289
- return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
1290
- var validation, isValid, date, monitor;
1291
- var _this = this;
1292
- return __generator(this, function (_b) {
1293
- if (!doc._id) {
1294
- doc._id = objectIdHexString();
1295
- }
1296
- if (this.checkSchema && !bypassCheckSchema) {
1297
- validation = this.simplschema.newContext();
1298
- isValid = validation.validate(doc);
1299
- if (!isValid) {
1300
- console.log(new Date(), this.collectionName, 'Schema Errors - insertOne', validation.validationErrors());
1301
- index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal.call(index_1.ResolveIOServer.getMainServer().getMethodManager(), 'insertErrorLog', 'Schema Failed on insertOne - ' + this.collectionName, [validation.validationErrors(), doc]);
1302
- reject(validation.validationErrors());
1303
- return [2 /*return*/];
1304
- }
1305
- }
1306
- if (this.timestamps) {
1307
- date = new Date();
1308
- doc.createdAt = date;
1309
- doc.updatedAt = date;
1310
- }
1311
- if (this.createLogs && !bypassLogs) {
1312
- log_collection_1.Logs.insertOne({
1313
- _id: objectIdHexString(),
1314
- type: 'document',
1315
- collection: this.collectionName,
1316
- id_document: doc._id,
1317
- payload: (0, common_1.getBinarySize)(JSON.stringify([doc, options])) < 200000 ? JSON.stringify([doc, options], null, 2) : 'Too Big',
1318
- method: 'insertOne',
1319
- id_user: '',
1320
- user: '',
1321
- messageId: 0,
1322
- route: ''
1323
- });
1324
- }
1325
- if (this.useVersions && !doc.hasOwnProperty('__v')) {
1326
- doc.__v = 0;
1327
- }
1328
- monitor = new monitor_manager_1.MonitorMongo('insertOne', this.collectionName, JSON.stringify([doc, options]));
1329
- index_1.ResolveIOServer.getMainDB().collection(this.collectionName, this.collectionOptions).insertOne(doc, options).then(function (res) {
1330
- monitor.finish();
1331
- if (res.acknowledged) {
1332
- index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(_this.collectionName);
1333
- resolve(doc);
1334
- }
1335
- else {
1336
- reject(res.acknowledged);
1337
- }
1338
- }, function (err) {
1339
- monitor.finish();
1340
- console.log(new Date(), 'Error Insert One', _this.collectionName, doc, options, err);
1341
- reject(err);
1342
- });
1343
- return [2 /*return*/];
1344
- });
1345
- }); });
1346
- };
1347
- MongoManagerCollection.prototype.listIndexes = function (options) {
1348
- var monitor = new monitor_manager_1.MonitorMongo('listIndexes', this.collectionName, JSON.stringify([options]));
1349
- var cursor = index_1.ResolveIOServer.getMainDB().collection(this.collectionName, this.collectionOptions).listIndexes(options);
1350
- cursor.on('close', function (ev) {
1351
- monitor.finish();
1352
- return ev;
1353
- });
1354
- return cursor;
1355
- };
1356
- MongoManagerCollection.prototype.rename = function (newName, options) {
1357
- var _this = this;
1358
- return new Promise(function (resolve, reject) {
1359
- var monitor = new monitor_manager_1.MonitorMongo('rename', _this.collectionName, JSON.stringify([newName, options]));
1360
- index_1.ResolveIOServer.getMainDB().collection(_this.collectionName, _this.collectionOptions).rename(newName, options).then(function (res) {
1361
- monitor.finish();
1362
- resolve(res);
1363
- }, function (err) {
1364
- monitor.finish();
1365
- console.log(new Date(), 'Error Rename', _this.collectionName, newName, options, err);
1366
- reject(err);
1367
- });
1368
- });
1369
- };
1370
- MongoManagerCollection.prototype.replaceOne = function (filter, replacement, options, bypassLogs, bypassCheckSchema, doc) {
1371
- var _this = this;
1372
- if (bypassLogs === void 0) { bypassLogs = false; }
1373
- if (bypassCheckSchema === void 0) { bypassCheckSchema = false; }
1374
- if (doc === void 0) { doc = null; }
1375
- return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
1376
- var validation, isValid, date, versionDoc, monitor_8, prevDoc, docId, docVersion, updatedDoc_1, monitor_9, monitor_10, monitor_11, monitor_12;
1377
- var _this = this;
1378
- return __generator(this, function (_b) {
1379
- switch (_b.label) {
1380
- case 0:
1381
- if (this.checkSchema && !bypassCheckSchema) {
1382
- validation = this.simplschema.newContext();
1383
- isValid = validation.validate(replacement);
1384
- if (!isValid) {
1385
- console.log(new Date(), this.collectionName, 'Schema Errors - replaceOne', validation.validationErrors());
1386
- index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal.call(index_1.ResolveIOServer.getMainServer().getMethodManager(), 'insertErrorLog', 'Schema Failed on replaceOne - ' + this.collectionName, [validation.validationErrors(), replacement]);
1387
- reject(validation.validationErrors());
1388
- return [2 /*return*/];
1389
- }
1390
- }
1391
- date = new Date();
1392
- if (this.timestamps) {
1393
- replacement.updatedAt = date;
1394
- }
1395
- if (!this.useVersions) return [3 /*break*/, 8];
1396
- if (!!doc) return [3 /*break*/, 2];
1397
- return [4 /*yield*/, this.findOne(filter, null, true)];
1398
- case 1:
1399
- doc = _b.sent();
1400
- _b.label = 2;
1401
- case 2:
1402
- if (!doc) return [3 /*break*/, 6];
1403
- if (this.timestamps && !replacement.createdAt && doc.createdAt) {
1404
- replacement.createdAt = doc.createdAt;
1405
- }
1406
- if (!(doc.__v === replacement.__v)) return [3 /*break*/, 3];
1407
- replacement.__v += 1;
1408
- versionDoc = (0, common_1.deepCopy)(doc);
1409
- versionDoc._id = { _id: doc._id, __v: doc.__v };
1410
- index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).replaceOne({ _id: { _id: doc._id, __v: doc.__v } }, versionDoc, { upsert: true });
1411
- if (doc.__v >= 4) {
1412
- index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).deleteMany({ $and: [{ '_id._id': doc._id }, { '_id.__v': { $lt: doc.__v - 4 } }] });
1413
- }
1414
- if (this.createLogs && !bypassLogs) {
1415
- log_collection_1.Logs.insertOne({
1416
- _id: objectIdHexString(),
1417
- type: 'document',
1418
- collection: this.collectionName,
1419
- id_document: doc._id,
1420
- payload: (0, common_1.getBinarySize)(JSON.stringify([doc, filter, replacement, options])) < 200000 ? JSON.stringify([doc, filter, replacement, options], null, 2) : 'Too Big',
1421
- method: 'replaceOne',
1422
- id_user: '',
1423
- user: '',
1424
- messageId: 0,
1425
- route: ''
1426
- });
1427
- }
1428
- monitor_8 = new monitor_manager_1.MonitorMongo('replaceOne', this.collectionName, JSON.stringify([filter, replacement, options]));
1429
- index_1.ResolveIOServer.getMainDB().collection(this.collectionName, this.collectionOptions).replaceOne(filter, replacement, options).then(function (res) {
1430
- monitor_8.finish();
1431
- if (res.acknowledged) {
1432
- index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(_this.collectionName);
1433
- resolve(res.modifiedCount);
1434
- }
1435
- else {
1436
- reject(res.acknowledged);
1437
- }
1438
- }, function (err) {
1439
- monitor_8.finish();
1440
- console.log(new Date(), 'Error Replace One', _this.collectionName, filter, replacement, options, err);
1441
- reject(err);
1442
- });
1443
- return [3 /*break*/, 5];
1444
- case 3:
1445
- console.log('invalid version - ' + this.collectionName, doc.__v, replacement.__v);
1446
- return [4 /*yield*/, index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).findOne({
1447
- _id: {
1448
- _id: doc._id,
1449
- __v: replacement.__v
1450
- }
1451
- }, null, true)];
1452
- case 4:
1453
- prevDoc = _b.sent();
1454
- if (prevDoc) {
1455
- docId = doc._id;
1456
- docVersion = doc.__v;
1457
- updatedDoc_1 = (0, common_1.getMongoMergeUpdatedDoc)(replacement, doc, prevDoc);
1458
- updatedDoc_1._id = docId;
1459
- updatedDoc_1.__v = docVersion + 1;
1460
- if (this.createLogs && !bypassLogs) {
1461
- log_collection_1.Logs.insertOne({
1462
- _id: objectIdHexString(),
1463
- type: 'document',
1464
- collection: this.collectionName,
1465
- id_document: docId,
1466
- payload: (0, common_1.getBinarySize)(JSON.stringify(['invalidVersion - merge', doc, filter, updatedDoc_1, options])) < 200000 ? JSON.stringify(['invalidVersion - merge', doc, filter, updatedDoc_1, options], null, 2) : 'Too Big',
1467
- method: 'replaceOne',
1468
- id_user: '',
1469
- user: '',
1470
- messageId: 0,
1471
- route: ''
1472
- });
1473
- }
1474
- monitor_9 = new monitor_manager_1.MonitorMongo('replaceOne', this.collectionName, JSON.stringify([filter, updatedDoc_1, options]));
1475
- index_1.ResolveIOServer.getMainDB().collection(this.collectionName, this.collectionOptions).replaceOne(filter, updatedDoc_1, options).then(function (res) {
1476
- monitor_9.finish();
1477
- if (res.acknowledged) {
1478
- index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(_this.collectionName);
1479
- resolve(res.modifiedCount);
1480
- }
1481
- else {
1482
- reject(res.acknowledged);
1483
- }
1484
- }, function (err) {
1485
- monitor_9.finish();
1486
- console.log(new Date(), 'Error Replace One', _this.collectionName, filter, updatedDoc_1, options, err);
1487
- reject(err);
1488
- });
1489
- }
1490
- else {
1491
- reject('Invalid Version And Could Not Find History - DB: ' + doc.__v + ', Trying to update with :' + replacement.__v);
1492
- }
1493
- _b.label = 5;
1494
- case 5: return [3 /*break*/, 7];
1495
- case 6:
1496
- if (options && options.upsert) {
1497
- if (this.timestamps) {
1498
- replacement.createdAt = date;
1499
- }
1500
- if (!replacement._id) {
1501
- replacement._id = objectIdHexString();
1502
- }
1503
- replacement.__v = 0;
1504
- if (this.createLogs && !bypassLogs) {
1505
- log_collection_1.Logs.insertOne({
1506
- _id: objectIdHexString(),
1507
- type: 'document',
1508
- collection: this.collectionName,
1509
- id_document: replacement._id,
1510
- payload: (0, common_1.getBinarySize)(JSON.stringify(['upsert', filter, replacement, options])) < 200000 ? JSON.stringify(['upsert', filter, replacement, options], null, 2) : 'Too Big',
1511
- method: 'replaceOne',
1512
- id_user: '',
1513
- user: '',
1514
- messageId: 0,
1515
- route: ''
1516
- });
1517
- }
1518
- monitor_10 = new monitor_manager_1.MonitorMongo('replaceOne', this.collectionName, JSON.stringify([filter, replacement, options]));
1519
- index_1.ResolveIOServer.getMainDB().collection(this.collectionName, this.collectionOptions).replaceOne(filter, replacement, options).then(function (res) {
1520
- monitor_10.finish();
1521
- if (res.acknowledged) {
1522
- index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(_this.collectionName);
1523
- resolve(res.modifiedCount);
1524
- }
1525
- else {
1526
- reject(res.acknowledged);
1527
- }
1528
- }, function (err) {
1529
- monitor_10.finish();
1530
- console.log(new Date(), 'Error Replace One', _this.collectionName, filter, replacement, options, err);
1531
- reject(err);
1532
- });
1533
- }
1534
- else {
1535
- reject('No Document');
1536
- }
1537
- _b.label = 7;
1538
- case 7: return [3 /*break*/, 9];
1539
- case 8:
1540
- if (options && options.upsert) {
1541
- if (this.timestamps && !replacement.createdAt) {
1542
- replacement.createdAt = date;
1543
- }
1544
- if (!replacement._id) {
1545
- replacement._id = objectIdHexString();
1546
- }
1547
- replacement.__v = 0;
1548
- }
1549
- if (this.createLogs && !bypassLogs) {
1550
- if (!options) {
1551
- options = { returnDocument: 'before' };
1552
- }
1553
- else {
1554
- options.returnDocument = 'before';
1555
- }
1556
- monitor_11 = new monitor_manager_1.MonitorMongo('findOneAndReplace', this.collectionName, JSON.stringify([filter, replacement, options]));
1557
- index_1.ResolveIOServer.getMainDB().collection(this.collectionName, this.collectionOptions).findOneAndReplace(filter, replacement, options).then(function (res) {
1558
- monitor_11.finish();
1559
- var doc = res;
1560
- if (doc) {
1561
- log_collection_1.Logs.insertOne({
1562
- _id: objectIdHexString(),
1563
- type: 'document',
1564
- collection: _this.collectionName,
1565
- id_document: doc._id,
1566
- payload: (0, common_1.getBinarySize)(JSON.stringify([doc, filter, replacement, options])) < 200000 ? JSON.stringify([doc, filter, replacement, options], null, 2) : 'Too Big',
1567
- method: 'replaceOne',
1568
- id_user: '',
1569
- user: '',
1570
- messageId: 0,
1571
- route: ''
1572
- });
1573
- }
1574
- else {
1575
- log_collection_1.Logs.insertOne({
1576
- _id: objectIdHexString(),
1577
- type: 'document',
1578
- collection: _this.collectionName,
1579
- id_document: replacement._id,
1580
- payload: (0, common_1.getBinarySize)(JSON.stringify(['upsert', filter, replacement, options])) < 200000 ? JSON.stringify(['upsert', filter, replacement, options], null, 2) : 'Too Big',
1581
- method: 'replaceOne',
1582
- id_user: '',
1583
- user: '',
1584
- messageId: 0,
1585
- route: ''
1586
- });
1587
- }
1588
- index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(_this.collectionName);
1589
- resolve(1);
1590
- }, function (err) {
1591
- monitor_11.finish();
1592
- console.log(new Date(), 'Error Find One And Replace', _this.collectionName, filter, replacement, options, err);
1593
- reject(err);
1594
- });
1595
- }
1596
- else {
1597
- monitor_12 = new monitor_manager_1.MonitorMongo('replaceOne', this.collectionName, JSON.stringify([filter, replacement, options]));
1598
- index_1.ResolveIOServer.getMainDB().collection(this.collectionName, this.collectionOptions).replaceOne(filter, replacement, options).then(function (res) {
1599
- monitor_12.finish();
1600
- if (res.acknowledged) {
1601
- index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(_this.collectionName);
1602
- resolve(res.modifiedCount);
1603
- }
1604
- else {
1605
- reject(res.acknowledged);
1606
- }
1607
- }, function (err) {
1608
- monitor_12.finish();
1609
- console.log(new Date(), 'Error Replace One', _this.collectionName, filter, replacement, options, err);
1610
- reject(err);
1611
- });
1612
- }
1613
- _b.label = 9;
1614
- case 9: return [2 /*return*/];
1615
- }
1616
- });
1617
- }); });
1618
- };
1619
- MongoManagerCollection.prototype.updateMany = function (filter, update, options, bypassLogs, bypassCheckSchema, bypassVersions) {
1620
- var _this = this;
1621
- if (bypassLogs === void 0) { bypassLogs = false; }
1622
- if (bypassCheckSchema === void 0) { bypassCheckSchema = false; }
1623
- if (bypassVersions === void 0) { bypassVersions = false; }
1624
- return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
1625
- var date, validation, isValid, docs, i, doc, versionDoc, monitor;
1626
- var _this = this;
1627
- return __generator(this, function (_b) {
1628
- switch (_b.label) {
1629
- case 0:
1630
- if ((!update.$inc || JSON.stringify(update.$inc) === '{}') && (!update.$set || JSON.stringify(update.$set) === '{}') && (!update.$setOnInsert || JSON.stringify(update.$setOnInsert) === '{}') && (!update.$unset || JSON.stringify(update.$unset) === '{}')) {
1631
- resolve(1);
1632
- return [2 /*return*/];
1633
- }
1634
- if (this.timestamps) {
1635
- date = new Date();
1636
- if (!update.$set) {
1637
- update.$set = { updatedAt: date };
1638
- }
1639
- else {
1640
- update.$set.updatedAt = date;
1641
- }
1642
- }
1643
- if (this.checkSchema && !bypassCheckSchema) {
1644
- validation = this.simplschema.newContext();
1645
- isValid = validation.validate(update, { modifier: true });
1646
- if (!isValid) {
1647
- console.log(new Date(), this.collectionName, 'Schema Errors - updateMany', validation.validationErrors());
1648
- index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal.call(index_1.ResolveIOServer.getMainServer().getMethodManager(), 'insertErrorLog', 'Schema Failed on updateMany - ' + this.collectionName, [validation.validationErrors(), update]);
1649
- reject(validation.validationErrors());
1650
- return [2 /*return*/];
1651
- }
1652
- }
1653
- if (!((this.useVersions && !bypassVersions) || (this.createLogs && !bypassLogs))) return [3 /*break*/, 2];
1654
- return [4 /*yield*/, this.find(filter)];
1655
- case 1:
1656
- docs = _b.sent();
1657
- for (i = 0; i < docs.length; i++) {
1658
- doc = docs[i];
1659
- if (this.createLogs && !bypassLogs) {
1660
- log_collection_1.Logs.insertOne({
1661
- _id: objectIdHexString(),
1662
- type: 'document',
1663
- collection: this.collectionName,
1664
- id_document: doc._id,
1665
- payload: (0, common_1.getBinarySize)(JSON.stringify([doc, filter, update, options])) < 200000 ? JSON.stringify([doc, filter, update, options], null, 2) : 'Too Big',
1666
- method: 'updateMany',
1667
- id_user: '',
1668
- user: '',
1669
- messageId: 0,
1670
- route: ''
1671
- });
1672
- }
1673
- if (this.useVersions) {
1674
- versionDoc = (0, common_1.deepCopy)(doc);
1675
- versionDoc._id = { _id: doc._id, __v: doc.__v };
1676
- index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).replaceOne({ _id: { _id: doc._id, __v: doc.__v } }, versionDoc, { upsert: true });
1677
- if (doc.__v >= 4) {
1678
- index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).deleteMany({ $and: [{ '_id._id': doc._id }, { '_id.__v': { $lt: doc.__v - 4 } }] });
1679
- }
1680
- if (!objectContainsPropertyDeep(update, '__v')) {
1681
- if (!update.$inc) {
1682
- update.$inc = { __v: 1 };
1683
- }
1684
- else if (!update.$inc.__v) {
1685
- update.$inc.__v = 1;
1686
- }
1687
- }
1688
- }
1689
- }
1690
- _b.label = 2;
1691
- case 2:
1692
- monitor = new monitor_manager_1.MonitorMongo('updateMany', this.collectionName, JSON.stringify([filter, update, options]));
1693
- index_1.ResolveIOServer.getMainDB().collection(this.collectionName, this.collectionOptions).updateMany(filter, update, options).then(function (res) {
1694
- monitor.finish();
1695
- if (res.acknowledged) {
1696
- index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(_this.collectionName);
1697
- resolve(res.modifiedCount);
1698
- }
1699
- else {
1700
- reject(res.acknowledged);
1701
- }
1702
- }, function (err) {
1703
- monitor.finish();
1704
- console.log(new Date(), 'Error Update Many', _this.collectionName, filter, update, options, err);
1705
- reject(err);
1706
- });
1707
- return [2 /*return*/];
1708
- }
1709
- });
1710
- }); });
1711
- };
1712
- MongoManagerCollection.prototype.updateOne = function (filter, update, options, bypassLogs, bypassCheckSchema) {
1713
- var _this = this;
1714
- if (bypassLogs === void 0) { bypassLogs = false; }
1715
- if (bypassCheckSchema === void 0) { bypassCheckSchema = false; }
1716
- return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
1717
- var validation, isValid, date, doc, versionDoc, monitor_13, monitor_14, monitor_15, monitor_16;
1718
- var _this = this;
1719
- return __generator(this, function (_b) {
1720
- switch (_b.label) {
1721
- case 0:
1722
- if (this.checkSchema && !bypassCheckSchema) {
1723
- validation = this.simplschema.newContext();
1724
- isValid = validation.validate(update, { modifier: true });
1725
- if (!isValid) {
1726
- console.log(new Date(), this.collectionName, 'Schema Errors - updateOne', validation.validationErrors());
1727
- index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal.call(index_1.ResolveIOServer.getMainServer().getMethodManager(), 'insertErrorLog', 'Schema Failed on updateOne - ' + this.collectionName, [validation.validationErrors(), update]);
1728
- reject(validation.validationErrors());
1729
- return [2 /*return*/];
1730
- }
1731
- }
1732
- if ((!update.$inc || JSON.stringify(update.$inc) === '{}') && (!update.$set || JSON.stringify(update.$set) === '{}') && (!update.$setOnInsert || JSON.stringify(update.$setOnInsert) === '{}') && (!update.$unset || JSON.stringify(update.$unset) === '{}')) {
1733
- resolve(1);
1734
- return [2 /*return*/];
1735
- }
1736
- date = new Date();
1737
- if (this.timestamps) {
1738
- if (!update.$set) {
1739
- update.$set = { updatedAt: date };
1740
- }
1741
- else {
1742
- update.$set.updatedAt = date;
1743
- }
1744
- }
1745
- if (!this.useVersions) return [3 /*break*/, 2];
1746
- return [4 /*yield*/, this.findOne(filter, null, true)];
1747
- case 1:
1748
- doc = _b.sent();
1749
- if (doc) {
1750
- if (this.createLogs && !bypassLogs) {
1751
- log_collection_1.Logs.insertOne({
1752
- _id: objectIdHexString(),
1753
- type: 'document',
1754
- collection: this.collectionName,
1755
- id_document: doc._id,
1756
- payload: (0, common_1.getBinarySize)(JSON.stringify([doc, filter, update, options])) < 200000 ? JSON.stringify([doc, filter, update, options], null, 2) : 'Too Big',
1757
- method: 'updateOne',
1758
- id_user: '',
1759
- user: '',
1760
- messageId: 0,
1761
- route: ''
1762
- });
1763
- }
1764
- versionDoc = (0, common_1.deepCopy)(doc);
1765
- versionDoc._id = { _id: doc._id, __v: doc.__v };
1766
- index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).replaceOne({ _id: { _id: doc._id, __v: doc.__v } }, versionDoc, { upsert: true });
1767
- if (doc.__v >= 4) {
1768
- index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).deleteMany({ $and: [{ '_id._id': doc._id }, { '_id.__v': { $lt: doc.__v - 4 } }] });
1769
- }
1770
- if (!objectContainsPropertyDeep(update, '__v')) {
1771
- if (!update.$inc) {
1772
- update.$inc = { __v: 1 };
1773
- }
1774
- else if (!update.$inc.__v) {
1775
- update.$inc.__v = 1;
1776
- }
1777
- }
1778
- monitor_13 = new monitor_manager_1.MonitorMongo('updateOne', this.collectionName, JSON.stringify([filter, update, options]));
1779
- index_1.ResolveIOServer.getMainDB().collection(this.collectionName, this.collectionOptions).updateOne(filter, update, options).then(function (res) {
1780
- monitor_13.finish();
1781
- if (res.acknowledged) {
1782
- index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(_this.collectionName);
1783
- resolve(res.modifiedCount);
1784
- }
1785
- else {
1786
- reject(res.acknowledged);
1787
- }
1788
- }, function (err) {
1789
- monitor_13.finish();
1790
- console.log(new Date(), 'Error Update One', _this.collectionName, filter, update, options, err);
1791
- reject(err);
1792
- });
1793
- }
1794
- else if (options && options.upsert) {
1795
- if (!update.$setOnInsert) {
1796
- if (this.timestamps) {
1797
- update.$setOnInsert = {
1798
- _id: objectIdHexString(),
1799
- __v: 0,
1800
- createdAt: new Date()
1801
- };
1802
- }
1803
- else {
1804
- update.$setOnInsert = {
1805
- _id: objectIdHexString(),
1806
- __v: 0
1807
- };
1808
- }
1809
- }
1810
- else {
1811
- if (!update.$setOnInsert._id) {
1812
- update.$setOnInsert._id = objectIdHexString();
1813
- }
1814
- if (this.timestamps) {
1815
- update.$setOnInsert.createdAt = new Date();
1816
- }
1817
- }
1818
- if (this.createLogs && !bypassLogs) {
1819
- log_collection_1.Logs.insertOne({
1820
- _id: objectIdHexString(),
1821
- type: 'document',
1822
- collection: this.collectionName,
1823
- id_document: update.$setOnInsert._id,
1824
- payload: (0, common_1.getBinarySize)(JSON.stringify(['upsert', filter, update, options])) < 200000 ? JSON.stringify(['upsert', filter, update, options], null, 2) : 'Too Big',
1825
- method: 'updateOne',
1826
- id_user: '',
1827
- user: '',
1828
- messageId: 0,
1829
- route: ''
1830
- });
1831
- }
1832
- monitor_14 = new monitor_manager_1.MonitorMongo('updateOne', this.collectionName, JSON.stringify([filter, update, options]));
1833
- index_1.ResolveIOServer.getMainDB().collection(this.collectionName, this.collectionOptions).updateOne(filter, update, options).then(function (res) {
1834
- monitor_14.finish();
1835
- if (res.acknowledged) {
1836
- index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(_this.collectionName);
1837
- resolve(res.modifiedCount);
1838
- }
1839
- else {
1840
- reject(res.acknowledged);
1841
- }
1842
- }, function (err) {
1843
- monitor_14.finish();
1844
- console.log(new Date(), 'Error Update One', _this.collectionName, filter, update, options, err);
1845
- reject(err);
1846
- });
1847
- }
1848
- else {
1849
- reject('No Document');
1850
- }
1851
- return [3 /*break*/, 3];
1852
- case 2:
1853
- if (options && options.upsert) {
1854
- if (!update.$setOnInsert) {
1855
- if (this.timestamps) {
1856
- update.$setOnInsert = {
1857
- _id: objectIdHexString(),
1858
- createdAt: new Date()
1859
- };
1860
- }
1861
- else {
1862
- update.$setOnInsert = {
1863
- _id: objectIdHexString()
1864
- };
1865
- }
1866
- }
1867
- else {
1868
- if (!update.$setOnInsert._id) {
1869
- update.$setOnInsert._id = objectIdHexString();
1870
- }
1871
- if (this.timestamps) {
1872
- update.$setOnInsert.createdAt = new Date();
1873
- }
1874
- }
1875
- }
1876
- if (this.createLogs && !bypassLogs) {
1877
- if (!options) {
1878
- options = { returnDocument: 'before' };
1879
- }
1880
- else {
1881
- options.returnDocument = 'before';
1882
- }
1883
- monitor_15 = new monitor_manager_1.MonitorMongo('findOneAndUpdate', this.collectionName, JSON.stringify([filter, update, options]));
1884
- index_1.ResolveIOServer.getMainDB().collection(this.collectionName, this.collectionOptions).findOneAndUpdate(filter, update, options).then(function (res) {
1885
- monitor_15.finish();
1886
- var doc = res.value;
1887
- if (doc) {
1888
- log_collection_1.Logs.insertOne({
1889
- _id: objectIdHexString(),
1890
- type: 'document',
1891
- collection: _this.collectionName,
1892
- id_document: doc._id,
1893
- payload: (0, common_1.getBinarySize)(JSON.stringify([doc, filter, update, options])) < 200000 ? JSON.stringify([doc, filter, update, options], null, 2) : 'Too Big',
1894
- method: 'updateOne',
1895
- id_user: '',
1896
- user: '',
1897
- messageId: 0,
1898
- route: ''
1899
- });
1900
- resolve(res.ok);
1901
- }
1902
- else if (update.$setOnInsert) {
1903
- log_collection_1.Logs.insertOne({
1904
- _id: objectIdHexString(),
1905
- type: 'document',
1906
- collection: _this.collectionName,
1907
- id_document: update.$setOnInsert._id,
1908
- payload: (0, common_1.getBinarySize)(JSON.stringify(['upsert', filter, update, options])) < 200000 ? JSON.stringify(['upsert', filter, update, options], null, 2) : 'Too Big',
1909
- method: 'updateOne',
1910
- id_user: '',
1911
- user: '',
1912
- messageId: 0,
1913
- route: ''
1914
- });
1915
- index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(_this.collectionName);
1916
- resolve(res.ok);
1917
- }
1918
- else {
1919
- resolve(0);
1920
- }
1921
- }, function (err) {
1922
- monitor_15.finish();
1923
- console.log(new Date(), 'Error Find One And Update', _this.collectionName, filter, update, options, err);
1924
- reject(err);
1925
- });
1926
- }
1927
- else {
1928
- monitor_16 = new monitor_manager_1.MonitorMongo('updateOne', this.collectionName, JSON.stringify([filter, update, options]));
1929
- index_1.ResolveIOServer.getMainDB().collection(this.collectionName, this.collectionOptions).updateOne(filter, update, options).then(function (res) {
1930
- monitor_16.finish();
1931
- if (res.acknowledged) {
1932
- index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(_this.collectionName);
1933
- resolve(res.modifiedCount);
1934
- }
1935
- else {
1936
- reject(res.acknowledged);
1937
- }
1938
- }, function (err) {
1939
- monitor_16.finish();
1940
- console.log(new Date(), 'Error Update One', _this.collectionName, filter, update, options, err);
1941
- reject(err);
1942
- });
1943
- }
1944
- _b.label = 3;
1945
- case 3: return [2 /*return*/];
1946
- }
1947
- });
1948
- }); });
1949
- };
1950
- MongoManagerCollection.prototype.watchCollection = function (pipeline, options) {
1951
- if (pipeline === void 0) { pipeline = []; }
1952
- var stream = index_1.ResolveIOServer.getMainDB().collection(this.collectionName, this.collectionOptions).watch(pipeline, options);
1953
- return stream;
1954
- };
1955
- MongoManagerCollection.prototype.watchCollectionWithAggregate = function (pipeline, options) {
1956
- if (pipeline === void 0) { pipeline = []; }
1957
- var stream = index_1.ResolveIOServer.getMainDB().collection(this.collectionName, this.collectionOptions).watch(pipeline, options);
1958
- return stream;
1959
- };
1960
- var _a;
1961
- _a = MongoManagerCollection;
1962
- MongoManagerCollection.indexQueue = async_1.default.queue(function (task, callback) { return __awaiter(void 0, void 0, void 0, function () {
1963
- var action, collection, specs, options, dbCollection, monitor, createIndex;
1964
- return __generator(_a, function (_b) {
1965
- switch (_b.label) {
1966
- case 0:
1967
- action = task.action, collection = task.collection, specs = task.specs, options = task.options;
1968
- dbCollection = index_1.ResolveIOServer.getMainDB().collection(collection.collectionName, collection.collectionOptions);
1969
- if (!dbCollection) {
1970
- return [2 /*return*/, callback(new Error("Collection ".concat(collection.collectionName, " not found")))];
1971
- }
1972
- monitor = new monitor_manager_1.MonitorMongo(action, collection.collectionName, JSON.stringify([specs, options]));
1973
- createIndex = function () { return __awaiter(void 0, void 0, void 0, function () {
1974
- var result, err_1, existingIndexName, innerError_1;
1975
- return __generator(this, function (_b) {
1976
- switch (_b.label) {
1977
- case 0:
1978
- _b.trys.push([0, 2, , 9]);
1979
- return [4 /*yield*/, dbCollection[action].apply(dbCollection, __spreadArray(__spreadArray([], specs, false), [options], false))];
1980
- case 1:
1981
- result = _b.sent();
1982
- monitor.finish();
1983
- callback(null, result);
1984
- return [3 /*break*/, 9];
1985
- case 2:
1986
- err_1 = _b.sent();
1987
- if (!(err_1.code === 85 || err_1.message.includes('IndexOptionsConflict'))) return [3 /*break*/, 8];
1988
- _b.label = 3;
1989
- case 3:
1990
- _b.trys.push([3, 7, , 8]);
1991
- existingIndexName = collection.extractIndexNameFromError(err_1.message);
1992
- if (!existingIndexName) return [3 /*break*/, 6];
1993
- return [4 /*yield*/, dbCollection.dropIndex(existingIndexName)];
1994
- case 4:
1995
- _b.sent();
1996
- return [4 /*yield*/, createIndex()];
1997
- case 5: return [2 /*return*/, _b.sent()];
1998
- case 6: return [3 /*break*/, 8];
1999
- case 7:
2000
- innerError_1 = _b.sent();
2001
- callback(innerError_1);
2002
- return [3 /*break*/, 8];
2003
- case 8:
2004
- monitor.finish();
2005
- callback(err_1);
2006
- return [3 /*break*/, 9];
2007
- case 9: return [2 /*return*/];
2008
- }
2009
- });
2010
- }); };
2011
- return [4 /*yield*/, createIndex()];
2012
- case 1:
2013
- _b.sent();
2014
- return [2 /*return*/];
2015
- }
2016
- });
2017
- }); }, 1);
2018
- return MongoManagerCollection;
2019
- }());
2020
- exports.MongoManagerCollection = MongoManagerCollection;
2021
- var MongoManagerUserCollection = /** @class */ (function (_super) {
2022
- __extends(MongoManagerUserCollection, _super);
2023
- function MongoManagerUserCollection() {
2024
- return _super !== null && _super.apply(this, arguments) || this;
2025
- }
2026
- MongoManagerUserCollection.prototype.authenticate = function (user, password) {
2027
- var _this = this;
2028
- return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
2029
- var attemptsInterval, calculatedInterval;
2030
- var _this = this;
2031
- return __generator(this, function (_b) {
2032
- switch (_b.label) {
2033
- case 0:
2034
- attemptsInterval = Math.pow(100, Math.log(user.attempts + 1));
2035
- calculatedInterval = attemptsInterval < 300000 ? attemptsInterval : 300000;
2036
- if (!user.last) return [3 /*break*/, 3];
2037
- if (!(Date.now() - user.last.getTime() < calculatedInterval)) return [3 /*break*/, 2];
2038
- user.last = new Date();
2039
- return [4 /*yield*/, user_collection_1.Users.updateOne({ _id: user._id }, { $set: { last: user.last } })];
2040
- case 1:
2041
- _b.sent();
2042
- resolve({
2043
- data: null,
2044
- error: 'Attempt Too Soon'
2045
- });
2046
- return [2 /*return*/];
2047
- case 2: return [3 /*break*/, 4];
2048
- case 3:
2049
- user.last = new Date();
2050
- _b.label = 4;
2051
- case 4:
2052
- if (user.attempts >= 5) {
2053
- resolve({
2054
- data: null,
2055
- error: 'Too Many Attempts'
2056
- });
2057
- return [2 /*return*/];
2058
- }
2059
- if (!user.salt) {
2060
- resolve({
2061
- data: null,
2062
- error: 'No Salt Value Stored'
2063
- });
2064
- return [2 /*return*/];
2065
- }
2066
- pbkdf2(password, user.salt, {
2067
- iterations: 25000,
2068
- keylen: 512,
2069
- digestAlgorithm: 'sha256'
2070
- }, function (err, hashBuffer) { return __awaiter(_this, void 0, void 0, function () {
2071
- return __generator(this, function (_b) {
2072
- switch (_b.label) {
2073
- case 0:
2074
- if (err) {
2075
- return [2 /*return*/, reject(err)];
2076
- }
2077
- if (!scmp(hashBuffer, Buffer.from(user.hash, 'hex'))) return [3 /*break*/, 2];
2078
- user.last = new Date();
2079
- user.attempts = 0;
2080
- return [4 /*yield*/, user_collection_1.Users.updateOne({ _id: user._id }, { $set: { last: user.last, attempts: user.attempts } })];
2081
- case 1:
2082
- _b.sent();
2083
- resolve({
2084
- data: user,
2085
- error: ''
2086
- });
2087
- return [3 /*break*/, 4];
2088
- case 2:
2089
- user.last = new Date();
2090
- user.attempts = user.attempts + 1;
2091
- return [4 /*yield*/, user_collection_1.Users.updateOne({ _id: user._id }, { $set: { last: user.last, attempts: user.attempts } })];
2092
- case 3:
2093
- _b.sent();
2094
- if (user.attempts >= 5) {
2095
- resolve({
2096
- data: null,
2097
- error: 'Too Many Attempts'
2098
- });
2099
- }
2100
- else {
2101
- resolve({
2102
- data: null,
2103
- error: 'Invalid Username And Password'
2104
- });
2105
- }
2106
- _b.label = 4;
2107
- case 4: return [2 /*return*/];
2108
- }
2109
- });
2110
- }); });
2111
- return [2 /*return*/];
2112
- }
2113
- });
2114
- }); });
2115
- };
2116
- MongoManagerUserCollection.prototype.serializeUser = function () {
2117
- return function (user, cb) {
2118
- cb(null, user.username);
2119
- };
2120
- };
2121
- MongoManagerUserCollection.prototype.deserializeUser = function () {
2122
- return function (username, cb) {
2123
- user_collection_1.Users.findOne({ username: username }).then(function (res) {
2124
- cb(null, res);
2125
- }, function (err) {
2126
- cb(err, null);
2127
- });
2128
- };
2129
- };
2130
- MongoManagerUserCollection.prototype.setPassword = function (user, password) {
2131
- var _this = this;
2132
- return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
2133
- var saltBuffer, salt, hashRaw, hash;
2134
- return __generator(this, function (_b) {
2135
- switch (_b.label) {
2136
- case 0:
2137
- if (!!user) return [3 /*break*/, 1];
2138
- reject('No User');
2139
- return [3 /*break*/, 5];
2140
- case 1:
2141
- if (!!password) return [3 /*break*/, 2];
2142
- reject('No Password');
2143
- return [3 /*break*/, 5];
2144
- case 2: return [4 /*yield*/, randomBytes(32)];
2145
- case 3:
2146
- saltBuffer = _b.sent();
2147
- salt = saltBuffer.toString('hex');
2148
- return [4 /*yield*/, pbkdf2Promisified(password, salt, {
2149
- iterations: 25000,
2150
- keylen: 512,
2151
- digestAlgorithm: 'sha256'
2152
- })];
2153
- case 4:
2154
- hashRaw = _b.sent();
2155
- hash = Buffer.from(hashRaw, 'binary').toString('hex');
2156
- user_collection_1.Users.updateOne({ _id: user._id }, { $set: { hash: hash, salt: salt, services: {}, attempts: 0 } }).then(function (res) { return resolve(res); }, function (rej) { return reject(rej); });
2157
- _b.label = 5;
2158
- case 5: return [2 /*return*/];
2159
- }
2160
- });
2161
- }); });
2162
- };
2163
- ;
2164
- MongoManagerUserCollection.prototype.changePassword = function (user, oldPassword, newPassword) {
2165
- var _this = this;
2166
- return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
2167
- var authUser;
2168
- return __generator(this, function (_b) {
2169
- switch (_b.label) {
2170
- case 0:
2171
- if (!!user) return [3 /*break*/, 1];
2172
- reject('Missing User');
2173
- return [3 /*break*/, 4];
2174
- case 1:
2175
- if (!(!oldPassword || !newPassword)) return [3 /*break*/, 2];
2176
- reject('Missing Password');
2177
- return [3 /*break*/, 4];
2178
- case 2: return [4 /*yield*/, this.authenticate(user, oldPassword)];
2179
- case 3:
2180
- authUser = _b.sent();
2181
- if (!authUser['data']) {
2182
- reject(authUser['error']);
2183
- }
2184
- else {
2185
- this.setPassword(user, newPassword).then(function (res) { return resolve(res); }, function (rej) { return reject(rej); });
2186
- }
2187
- _b.label = 4;
2188
- case 4: return [2 /*return*/];
2189
- }
2190
- });
2191
- }); });
2192
- };
2193
- MongoManagerUserCollection.prototype.register = function (user, password) {
2194
- var _this = this;
2195
- return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
2196
- var dbUser;
2197
- return __generator(this, function (_b) {
2198
- switch (_b.label) {
2199
- case 0:
2200
- if (!!user.username) return [3 /*break*/, 1];
2201
- reject('Missing Username');
2202
- return [3 /*break*/, 5];
2203
- case 1: return [4 /*yield*/, user_collection_1.Users.findOne({ username: user.username })];
2204
- case 2:
2205
- dbUser = _b.sent();
2206
- if (!dbUser) return [3 /*break*/, 3];
2207
- reject('Username Exists');
2208
- return [3 /*break*/, 5];
2209
- case 3: return [4 /*yield*/, user_collection_1.Users.findOne({ email: user.email })];
2210
- case 4:
2211
- dbUser = _b.sent();
2212
- if (dbUser) {
2213
- reject('Email Exists');
2214
- }
2215
- else {
2216
- user.setPassword(password);
2217
- resolve(user);
2218
- }
2219
- _b.label = 5;
2220
- case 5: return [2 /*return*/];
2221
- }
2222
- });
2223
- }); });
2224
- };
2225
- MongoManagerUserCollection.prototype.resetAttempts = function (user) {
2226
- return user_collection_1.Users.updateOne({ _id: user._id }, { $set: { attempts: 0 } });
2227
- };
2228
- return MongoManagerUserCollection;
2229
- }(MongoManagerCollection));
2230
- exports.MongoManagerUserCollection = MongoManagerUserCollection;
2231
- function objectIdHexString() {
2232
- var objectId = new mongodb_1.ObjectId();
2233
- return objectId.toHexString();
2234
- }
2235
- exports.objectIdHexString = objectIdHexString;
2236
- function pbkdf2(password, salt, options, callback) {
2237
- crypto.pbkdf2(password, salt, options.iterations, options.keylen, options.digestAlgorithm, callback);
2238
- }
2239
- ;
2240
- function pbkdf2Promisified(password, salt, options) {
2241
- return new Promise(function (resolve, reject) { return pbkdf2(password, salt, options, function (err, hashRaw) { return (err ? reject(err) : resolve(hashRaw)); }); });
2242
- }
2243
- function randomBytes(saltlen) {
2244
- return new Promise(function (resolve, reject) { return crypto.randomBytes(saltlen, function (err, saltBuffer) { return (err ? reject(err) : resolve(saltBuffer)); }); });
2245
- }
2246
- function objectContainsPropertyDeep(obj, prop) {
2247
- var keys = Object.keys(obj);
2248
- if (keys.some(function (a) { return a === prop; })) {
2249
- return true;
2250
- }
2251
- for (var i = 0; i < keys.length; i++) {
2252
- var key = keys[i];
2253
- if (obj[key] && typeof obj[key] === 'object' && objectContainsPropertyDeep(obj[key], prop)) {
2254
- return true;
2255
- }
2256
- }
2257
- return false;
2258
- }
2259
-
1
+ "use strict";var __extends=this&&this.__extends||function(){var t=function(e,n){return(t=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(e,n){e.__proto__=n}:function(e,n){for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}))(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}}(),__awaiter=this&&this.__awaiter||function(e,c,a,l){return new(a=a||Promise)(function(o,n){function t(e){try{r(l.next(e))}catch(e){n(e)}}function i(e){try{r(l.throw(e))}catch(e){n(e)}}function r(e){var n;e.done?o(e.value):((n=e.value)instanceof a?n:new a(function(e){e(n)})).then(t,i)}r((l=l.apply(e,c||[])).next())})},__generator=this&&this.__generator||function(t,i){var r,c,a,l={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},s={next:e(0),throw:e(1),return:e(2)};return"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function e(o){return function(e){var n=[o,e];if(r)throw new TypeError("Generator is already executing.");for(;l=s&&n[s=0]?0:l;)try{if(r=1,c&&(a=2&n[0]?c.return:n[0]?c.throw||((a=c.return)&&a.call(c),0):c.next)&&!(a=a.call(c,n[1])).done)return a;switch(c=0,(n=a?[2&n[0],a.value]:n)[0]){case 0:case 1:a=n;break;case 4:return l.label++,{value:n[1],done:!1};case 5:l.label++,c=n[1],n=[0];continue;case 7:n=l.ops.pop(),l.trys.pop();continue;default:if(!(a=0<(a=l.trys).length&&a[a.length-1])&&(6===n[0]||2===n[0])){l=0;continue}if(3===n[0]&&(!a||n[1]>a[0]&&n[1]<a[3]))l.label=n[1];else if(6===n[0]&&l.label<a[1])l.label=a[1],a=n;else{if(!(a&&l.label<a[2])){a[2]&&l.ops.pop(),l.trys.pop();continue}l.label=a[2],l.ops.push(n)}}n=i.call(t,l)}catch(e){n=[6,e],c=0}finally{r=a=0}if(5&n[0])throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}}},__spreadArray=this&&this.__spreadArray||function(e,n,o){if(o||2===arguments.length)for(var t,i=0,r=n.length;i<r;i++)!t&&i in n||((t=t||Array.prototype.slice.call(n,0,i))[i]=n[i]);return e.concat(t||Array.prototype.slice.call(n))},simpl_schema_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.objectIdHexString=exports.MongoManagerUserCollection=exports.MongoManagerCollection=exports.MongoManagerModel=exports.MongoManager=void 0,require("simpl-schema")),mongodb_1=require("mongodb"),index_1=require("../index"),user_collection_1=require("../collections/user.collection"),common_1=require("../util/common"),log_collection_1=require("../collections/log.collection"),NodeCache=require("node-cache"),crypto=require("crypto"),scmp=require("scmp"),monitor_manager_1=require("./monitor.manager"),os_1=require("os"),numCPUs=(0,os_1.cpus)().length,v8=require("v8"),async_1=require("async"),MongoManager=function(){function e(){var e=this;this._collections=[],this._mongoQueue=[],this._mongoQueueId=0,this._mongoQueueRunning=!1,this._mongoQueueCacheId=1,this._heapStats=v8.getHeapStatistics(),this._heapLimit=this._heapStats.heap_size_limit/numCPUs/8,this._serverCollections=[],this._debugMongoQueueHits=0,this._debugRemoveCacheHits=0,this._debugMongoQueueCollections=[],this._nodeCache=new NodeCache({stdTTL:0,checkperiod:0}),setInterval(function(){index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&(console.log(new Date,"Mongo Manager","Collections",e._collections.length),console.log(new Date,"Mongo Manager","Mongo Queue",e._mongoQueue.length,JSON.stringify(e._mongoQueue.sort(function(e,n){return e.name_collection.localeCompare(n.name_collection)}),null,2)),console.log(new Date,"Mongo Manager","Server Collections",e._serverCollections.length),console.log(new Date,"Mongo Manager","Mongo Queue Hits",e._debugMongoQueueHits),console.log(new Date,"Mongo Manager","Mongo Queue Collections",e._debugMongoQueueCollections.sort(function(e,n){return e.collection.localeCompare(n.collection)||e.function.localeCompare(n.function)})),console.log(new Date,"Mongo Manager","Cache Cleanup Hits",JSON.stringify(e._debugRemoveCacheHits,null,2))),e._debugMongoQueueHits=0,e._debugRemoveCacheHits=0,e._debugMongoQueueCollections=[]},6e4),this.initServerCollections(),this.runQueue()}return e.prototype.initServerCollections=function(){return __awaiter(this,void 0,void 0,function(){var n;return __generator(this,function(e){switch(e.label){case 0:return[4,index_1.ResolveIOServer.getMainDB().listCollections().toArray()];case 1:return n=e.sent(),this._serverCollections=n,[2]}})})},e.prototype.getServerCollections=function(){return this._serverCollections},e.prototype.registerCollection=function(n){var e=this;n.collectionOptions&&n.collectionOptions.timeseries&&n.collectionOptions.timeseries.timeField&&this._serverCollections.some(function(e){return e.name===n.collectionName&&"collection"===e.type})&&index_1.ResolveIOServer.getMainDB().dropCollection(n.collectionName).then(function(){e.createCollection(n)}),this._collections.push(n)},e.prototype.createCollection=function(e){index_1.ResolveIOServer.getMainDB().createCollection(e.collectionName,e.collectionOptions)},e.prototype.collections=function(){return this._collections},e.prototype.collection=function(n){return this._collections.filter(function(e){return e.collectionName===n})[0]},e.prototype.addToQueue=function(n){var e=this._mongoQueue.filter(function(e){return e.name_collection===n.name_collection&&e.name_function===n.name_function&&e.name_function_addt===n.name_function_addt&&JSON.stringify(e.data_function)===JSON.stringify(n.data_function)&&JSON.stringify(e.data_function_addt)===JSON.stringify(n.data_function_addt)})[0];e?(e.running?e.cbs_next:e.cbs).push(n.cbs[0]):(n._id=this._mongoQueueId,this._mongoQueueId+=1,this._mongoQueue.splice(0,0,n))},e.prototype.runQueue=function(){return __awaiter(this,void 0,void 0,function(){var c=this;return __generator(this,function(e){return setInterval(function(){if(!c._mongoQueueRunning){var o=c._mongoQueue.filter(function(e){return!e.running&&e.cbs.length});if(o.length){c._mongoQueueRunning=!0;for(var e=o.length-1;0<=e;e--)!function(e){c._debugMongoQueueHits+=1;var t,i,r=o[e];if(c._debugMongoQueueCollections.some(function(e){return e.collection===r.name_collection&&e.function===r.name_function})?c._debugMongoQueueCollections.filter(function(e){return e.collection===r.name_collection&&e.function===r.name_function})[0].hits+=1:c._debugMongoQueueCollections.push({collection:r.name_collection,function:r.name_function,hits:1}),r.running=!0,r.invalidateFlag=!1,r.cacheId)try{var n=JSON.parse(c._nodeCache.get(r.cacheId),common_1.dateReviver);r.cbs.forEach(function(e){e(null,n,!0)}),r.cbs=[],r.running=!1}catch(e){r.cacheId=0}r.cacheId||(r.name_function_addt?(t=new monitor_manager_1.MonitorMongo(r.name_function,r.name_collection,JSON.stringify(__spreadArray(__spreadArray(__spreadArray([],r.data_function,!0),[r.name_function_addt],!1),r.data_function_addt,!0))),(e=(e=index_1.ResolveIOServer.getMainDB().collection(r.name_collection))[r.name_function].apply(e,r.data_function))[r.name_function_addt].apply(e,r.data_function_addt).then(function(n){if(t.finish(),r.invalidateFlag)5<=r.invalidateCount&&(r.invalidateCount=0,r.cbs.forEach(function(e){e(null,n,!1)})),r.cbs=r.cbs.concat(r.cbs_next),r.cbs_next=[];else{var e=r.invalidateCount=0,o=!1;try{e=JSON.stringify(n).replace(/[\[\]\,\"]/g,"").length}catch(e){o=!0}!o&&null!=n&&(!Array.isArray(n)||n.length)&&e<1e7?(r.cacheId=c._mongoQueueCacheId,c._mongoQueueCacheId+=1,c.addToCache(r.cacheId,n)):r.cacheId=0,r.cbs.forEach(function(e){e(null,n,!1)}),r.cbs_next.length?(r.cbs=r.cbs_next,r.cbs_next=[]):r.cbs=[]}r.running=!1},function(n){t.finish(),r.cbs.forEach(function(e){e(n,null,!1)}),r.cbs_next.forEach(function(e){e(n,null,!1)}),0<=c._mongoQueue.map(function(e){return e._id}).indexOf(r._id)&&c._mongoQueue.splice(c._mongoQueue.map(function(e){return e._id}).indexOf(r._id),1)})):(i=new monitor_manager_1.MonitorMongo(r.name_function,r.name_collection,JSON.stringify(r.data_function)),(e=index_1.ResolveIOServer.getMainDB().collection(r.name_collection))[r.name_function].apply(e,r.data_function).then(function(n){if(i.finish(),r.invalidateFlag)5<=r.invalidateCount&&(r.invalidateCount=0,r.cbs.forEach(function(e){e(null,n,!1)})),r.cbs=r.cbs.concat(r.cbs_next),r.cbs_next=[];else{var e=r.invalidateCount=0,o=!1;try{e=JSON.stringify(n).replace(/[\[\]\,\"]/g,"").length}catch(e){o=!0}!o&&null!=n&&(!Array.isArray(n)||n.length)&&e<1e7?(r.cacheId=c._mongoQueueCacheId,c._mongoQueueCacheId+=1,c.addToCache(r.cacheId,n)):r.cacheId=0,r.cbs.forEach(function(e){e(null,n,!1)}),r.cbs_next.length?(r.cbs=r.cbs_next,r.cbs_next=[]):r.cbs=[]}r.running=!1},function(n){i.finish(),console.log.apply(console,__spreadArray(__spreadArray([new Date,"Error "+r.name_function,r.name_collection],r.data_function,!1),[n],!1)),r.cbs.forEach(function(e){e(n,null,!1)}),r.cbs_next.forEach(function(e){e(n,null,!1)}),0<=c._mongoQueue.map(function(e){return e._id}).indexOf(r._id)&&c._mongoQueue.splice(c._mongoQueue.map(function(e){return e._id}).indexOf(r._id),1)})))}(e);c._mongoQueueRunning=!1}}},25),[2]})})},e.prototype.addToCache=function(e,n){var o=this._nodeCache.getStats().vsize;if(o>this._heapLimit){for(var t=0,i=this._mongoQueue.filter(function(e){return e.cacheId&&!e.running&&!e.cbs.length}),r=i.length-1;0<=r;r--){this._debugRemoveCacheHits+=1;var c=i[r];if(this._nodeCache.del(c.cacheId),(c.cacheId=0)<=this._mongoQueue.map(function(e){return e._id}).indexOf(c._id)&&this._mongoQueue.splice(this._mongoQueue.map(function(e){return e._id}).indexOf(c._id),1),t+=1,(o=this._nodeCache.getStats().vsize)<.75*this._heapLimit)break}console.log("Query Cache: Too Big, - Deleted: "+t+" - "+o)}this._nodeCache.set(e,JSON.stringify(n))},e.prototype.invalidateQueryCache=function(n){for(var e=this._mongoQueue.filter(function(e){return e.name_collection===n||e.lookup_collections.includes(n)}),o=e.length-1;0<=o;o--){var t=e[o];t.cacheId&&(this._nodeCache.del(t.cacheId),t.cacheId=0),t.running?(t.invalidateFlag=!0,t.invalidateCount+=1):t.cbs.length||0<=this._mongoQueue.map(function(e){return e._id}).indexOf(t._id)&&this._mongoQueue.splice(this._mongoQueue.map(function(e){return e._id}).indexOf(t._id),1)}},e}(),MongoManagerModel=(exports.MongoManager=MongoManager,function(e){var n;this.collection_main=null,this.collection_version=null,"users"===e.collectionName?this.collection_main=new MongoManagerUserCollection(e):this.collection_main=new MongoManagerCollection(e),e.useVersionCollection&&(this.collection_main.useVersions=!0,(n=(0,common_1.deepCopy)(e.schema))._id.type="Object",n._id.blackbox=!0,n={collectionName:e.collectionName+".versions",schema:n,useVersionCollection:!1,useReportBuilder:!1,reportBuilderLookupTables:[],timestamps:!0,createLogs:!1,checkSchema:!1,collectionOptions:null},"users"===e.collectionName?this.collection_version=new MongoManagerUserCollection(n):this.collection_version=new MongoManagerCollection(n),this.collection_version.createIndex({"_id._id":1,"_id.__v":1}),this.collection_main.versionCollection=e.collectionName+".versions")}),MongoManagerCollection=(exports.MongoManagerModel=MongoManagerModel,function(){function r(e){var n,o=this,t=(this.collectionName="",this.checkSchema=!1,this.simplschema=null,this.rbSchema=null,this.timestamps=!1,this.useVersions=!1,this.versionCollection="",this.createLogs=!0,this.useRB=!1,this.collectionName=e.collectionName,this.simplschema=new simpl_schema_1.default(e.schema),this.timestamps=e.timestamps,this.createLogs=e.createLogs,this.checkSchema=e.checkSchema,this.collectionOptions=e.collectionOptions,e.useReportBuilder&&(this.useRB=!0,n=(0,common_1.deepCopy)(e.schema),e=(0,common_1.buildRbLookups)(e.reportBuilderLookupTables,n,[]),this.rbSchema=(0,common_1.buildRbSchema)(e)),setInterval(function(){index_1.ResolveIOServer&&index_1.ResolveIOServer.getMainServer()&&index_1.ResolveIOServer.getMongoManager()&&index_1.ResolveIOServer.getMongoManager().getServerCollections().length&&(index_1.ResolveIOServer.getMongoManager().registerCollection(o),clearInterval(t))},1))}var e;return r.prototype.extractIndexNameFromError=function(e){var n=e.match(/Index already exists with a different name: (\S+)/);return(n=!n||n.length<=1?e.match(/existing index:.*name: "([^"]+)"/):n)&&1<n.length?n[1]:null},r.prototype.aggregate=function(i,r,e){var c=this;return void 0===e&&(e=!1),new Promise(function(n,o){var t=new monitor_manager_1.MonitorMongo("aggregate",c.collectionName,JSON.stringify([i,r]));index_1.ResolveIOServer.getMainDB().collection(c.collectionName,c.collectionOptions).aggregate(i,r).toArray().then(function(e){t.finish(),n(e)},function(e){t.finish(),console.log(new Date,"Error Aggregate",c.collectionName,i,r,e),o(e)})})},r.prototype.aggregateCount=function(e,n){var o=this;return new Promise(function(t,i){index_1.ResolveIOServer.getMongoManager().addToQueue({_id:0,name_collection:o.collectionName,name_function:"aggregate",name_function_addt:"count",data_function:[e,n],data_function_addt:[],cbs:[function(e,n,o){e?i(e):t(n)}],cbs_next:[],running:!1,cacheId:0,lookup_collections:e.filter(function(e){return e.$lookup&&e.$lookup.from}).map(function(e){return e.$lookup.from}).filter(function(e,n,o){return n===o.indexOf(e)}),invalidateFlag:!1,invalidateCount:0})})},r.prototype.aggregateCursor=function(e,n){var o=new monitor_manager_1.MonitorMongo("aggregateCursor",this.collectionName,JSON.stringify([e,n])),e=index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).aggregate(e,n);return e.on("close",function(e){return o.finish(),e}),e},r.prototype.aggregateStream=function(e,n,o){var t=new monitor_manager_1.MonitorMongo("aggregateStream",this.collectionName,JSON.stringify([e,n,o])),e=index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).aggregate(e,n).stream(o);return e.on("end",function(e){return t.finish(),e}).on("error",function(e){return t.finish(),e}).on("close",function(e){return t.finish(),e}),e},r.prototype.bulkWrite=function(i,r){var c=this;return new Promise(function(n,o){var t=new monitor_manager_1.MonitorMongo("bulkWrite",c.collectionName,JSON.stringify([i.slice(-100),r]));index_1.ResolveIOServer.getMainDB().collection(c.collectionName,c.collectionOptions).bulkWrite(i,r).then(function(e){t.finish(),n(e)},function(e){t.finish(),console.log(new Date,"Error Bulk Write",c.collectionName,i.slice(-100),r,e),o(e)})})},r.prototype.countDocuments=function(i,r){var c=this;return void 0===i&&(i={}),new Promise(function(n,o){var t=new monitor_manager_1.MonitorMongo("countDocuments",c.collectionName,JSON.stringify([i,r]));index_1.ResolveIOServer.getMainDB().collection(c.collectionName,c.collectionOptions).countDocuments(i,r).then(function(e){t.finish(),n(e)},function(e){t.finish(),console.log(new Date,"Error Count Documents",c.collectionName,i,r,e),o(e)})})},r.prototype.create=function(e,n){return Array.isArray(e)?1===e.length?this.insertOne(e[0],n):this.insertMany(e,n):this.insertOne(e,n)},r.prototype.createIndex=function(e,n){var i=this;return new Promise(function(o,t){r.indexQueue.push({action:"createIndex",collection:i,specs:[e],options:n},function(e,n){e?t(e):o(n)})})},r.prototype.createIndexes=function(e,n){var i=this;return new Promise(function(o,t){r.indexQueue.push({action:"createIndexes",collection:i,specs:[e],options:n},function(e,n){e?t(e):o(n)})})},r.prototype.deleteMany=function(s,d,u){var e=this;return void 0===s&&(s={}),void 0===u&&(u=!1),new Promise(function(a,l){return __awaiter(e,void 0,void 0,function(){var n,o,t,i,r,c=this;return __generator(this,function(e){switch(e.label){case 0:return!this.createLogs||u?[3,2]:[4,this.find(s)];case 1:for(n=e.sent(),o=0;o<n.length;o++)t=n[o],log_collection_1.Logs.insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:t._id,payload:(0,common_1.getBinarySize)(JSON.stringify([t,s,d]))<2e5?JSON.stringify([t,s,d],null,2):"Too Big",method:"deleteMany",id_user:"",user:"",messageId:0,route:""}),this.useVersions&&((i=(0,common_1.deepCopy)(t))._id={_id:t._id,__v:t.__v},index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).replaceOne({_id:{_id:t._id,__v:t.__v}},i,{upsert:!0}),index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).deleteMany({$and:[{"_id._id":t._id},{"_id.__v":{$lt:t.__v-1}}]}));e.label=2;case 2:return r=new monitor_manager_1.MonitorMongo("deleteMany",this.collectionName,JSON.stringify([s,d])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).deleteMany(s,d).then(function(e){r.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(c.collectionName),a(e.deletedCount)):l(e.acknowledged)},function(e){r.finish(),console.log(new Date,"Error Delete Many",c.collectionName,s,d,e),l(e)}),[2]}})})})},r.prototype.deleteOne=function(c,a,l){var e=this;return void 0===c&&(c={}),void 0===l&&(l=!1),new Promise(function(r,t){return __awaiter(e,void 0,void 0,function(){var i,n,o=this;return __generator(this,function(e){return this.createLogs&&!l?(i=new monitor_manager_1.MonitorMongo("findOneAndDelete",this.collectionName,JSON.stringify([c,a])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).findOneAndDelete(c,a).then(function(t){return __awaiter(o,void 0,void 0,function(){var n,o;return __generator(this,function(e){return i.finish(),(n=t)?(this.createLogs&&!l&&log_collection_1.Logs.insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:n._id,payload:(0,common_1.getBinarySize)(JSON.stringify([n,c,a]))<2e5?JSON.stringify([n,c,a],null,2):"Too Big",method:"deleteOne",id_user:"",user:"",messageId:0,route:""}),this.useVersions&&((o=(0,common_1.deepCopy)(n))._id={_id:n._id,__v:n.__v},index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).replaceOne({_id:{_id:n._id,__v:n.__v}},o,{upsert:!0}),index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).deleteMany({$and:[{"_id._id":n._id},{"_id.__v":{$lt:n.__v-1}}]})),index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(this.collectionName),r(1)):r(0),[2]})})},function(e){i.finish(),console.log(new Date,"Error Find One And Delete",o.collectionName,c,a,e),t(e)})):(n=new monitor_manager_1.MonitorMongo("deleteOne",this.collectionName,JSON.stringify([c,a])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).deleteOne(c,a).then(function(e){n.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(o.collectionName),r(e.deletedCount)):t(e.acknowledged)},function(e){n.finish(),console.log(new Date,"Error Delete One",o.collectionName,c,a,e),t(e)})),[2]})})})},r.prototype.distinct=function(e,i,r){var c=this;return new Promise(function(n,o){var t=new monitor_manager_1.MonitorMongo("distinct",c.collectionName,JSON.stringify([e,i,r]));index_1.ResolveIOServer.getMainDB().collection(c.collectionName,c.collectionOptions).distinct(e,i,r).then(function(e){t.finish(),n(e)},function(e){t.finish(),console.log(new Date,"Error Distinct",c.collectionName,i,r,e),o(e)})})},r.prototype.drop=function(i){var r=this;return new Promise(function(n,o){var t=new monitor_manager_1.MonitorMongo("drop",r.collectionName,JSON.stringify([i]));index_1.ResolveIOServer.getMainDB().collection(r.collectionName,r.collectionOptions).drop(i).then(function(e){t.finish(),n(e)},function(e){t.finish(),console.log(new Date,"Error Count Documents",r.collectionName,i,e),o(e)})})},r.prototype.dropIndex=function(i,r){var c=this;return new Promise(function(n,o){var t=new monitor_manager_1.MonitorMongo("dropIndex",c.collectionName,JSON.stringify([i,r]));index_1.ResolveIOServer.getMainDB().collection(c.collectionName,c.collectionOptions).dropIndex(i,r).then(function(e){t.finish(),n(e)},function(e){t.finish(),console.log(new Date,"Error Drop Index",c.collectionName,i,r,e),o(e)})})},r.prototype.dropIndexes=function(i){var r=this;return new Promise(function(n,o){var t=new monitor_manager_1.MonitorMongo("dropIndexes",r.collectionName,JSON.stringify([i]));index_1.ResolveIOServer.getMainDB().collection(r.collectionName,r.collectionOptions).dropIndexes(i).then(function(e){t.finish(),n(e)},function(e){t.finish(),console.log(new Date,"Error Drop Indexes",r.collectionName,i,e),o(e)})})},r.prototype.find=function(r,c,a){var e=this;return void 0===r&&(r={}),void 0===a&&(a=!1),new Promise(function(t,i){return __awaiter(e,void 0,void 0,function(){var n,o=this;return __generator(this,function(e){return a?(n=new monitor_manager_1.MonitorMongo("find",this.collectionName,JSON.stringify([r,c])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).find(r,c).toArray().then(function(e){n.finish(),t(e)},function(e){n.finish(),console.log(new Date,"Error Find",o.collectionName,r,c,e),i(e)})):index_1.ResolveIOServer.getMongoManager().addToQueue({_id:0,name_collection:this.collectionName,name_function:"find",name_function_addt:"toArray",data_function:[r,c],data_function_addt:[],cbs:[function(e,n,o){e?i(e):t(n)}],cbs_next:[],running:!1,cacheId:0,lookup_collections:[],invalidateFlag:!1,invalidateCount:0}),[2]})})})},r.prototype.findById=function(i,r){var c=this;return new Promise(function(n,o){var t=new monitor_manager_1.MonitorMongo("findById",c.collectionName,JSON.stringify([{_id:i},r]));index_1.ResolveIOServer.getMainDB().collection(c.collectionName,c.collectionOptions).findOne({_id:i},r).then(function(e){t.finish(),n(e)},function(e){t.finish(),console.log(new Date,"Error Find By Id",c.collectionName,{_id:i},r,e),o(e)})})},r.prototype.findCount=function(i,r){var c=this;return void 0===i&&(i={}),new Promise(function(n,o){var t=new monitor_manager_1.MonitorMongo("findCount",c.collectionName,JSON.stringify([i,r]));index_1.ResolveIOServer.getMainDB().collection(c.collectionName,c.collectionOptions).find(i,r).count().then(function(e){t.finish(),n(e)},function(e){t.finish(),console.log(new Date,"Error Find Count",c.collectionName,i,r,e),o(e)})})},r.prototype.findCursor=function(e,n){void 0===e&&(e={});var o=new monitor_manager_1.MonitorMongo("findCursor",this.collectionName,JSON.stringify([e,n])),t=index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).find(e,n);return t.on("close",function(e){return o.finish(),t.removeAllListeners(),e}),t},r.prototype.findStream=function(e,n,o){void 0===e&&(e={});var t=new monitor_manager_1.MonitorMongo("findStream",this.collectionName,JSON.stringify([e,n,o])),e=index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).find(e,n).stream(o);return e.on("end",function(e){return t.finish(),e}).on("error",function(e){return t.finish(),e}).on("close",function(e){return t.finish(),e}),e},r.prototype.findOne=function(o,r,e){var c=this;return void 0===o&&(o={}),void 0===e&&(e=!1),new Promise(function(t,i){var n;e?(n=new monitor_manager_1.MonitorMongo("findOne",c.collectionName,JSON.stringify([o,r])),index_1.ResolveIOServer.getMainDB().collection(c.collectionName,c.collectionOptions).findOne(o,r).then(function(e){n.finish(),t(e)},function(e){n.finish(),console.log(new Date,"Error Find One",c.collectionName,o,r,e),i(e)})):index_1.ResolveIOServer.getMongoManager().addToQueue({_id:0,name_collection:c.collectionName,name_function:"findOne",name_function_addt:"",data_function:[o,r],data_function_addt:[],cbs:[function(e,n,o){e?i(e):t(n)}],cbs_next:[],running:!1,cacheId:0,lookup_collections:[],invalidateFlag:!1,invalidateCount:0})})},r.prototype.findOneAndDelete=function(r,c,a){var e=this;return void 0===r&&(r={}),void 0===a&&(a=!1),new Promise(function(i,n){return __awaiter(e,void 0,void 0,function(){var o,t=this;return __generator(this,function(e){return o=new monitor_manager_1.MonitorMongo("findOneAndDelete",this.collectionName,JSON.stringify([r,c])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).findOneAndDelete(r,c).then(function(e){o.finish();var n;e?(t.createLogs&&!a&&log_collection_1.Logs.insertOne({_id:objectIdHexString(),type:"document",collection:t.collectionName,id_document:e._id,payload:(0,common_1.getBinarySize)(JSON.stringify([e,r,c]))<2e5?JSON.stringify([e,r,c],null,2):"Too Big",method:"findOneAndDelete",id_user:"",user:"",messageId:0,route:""}),t.useVersions&&((n=(0,common_1.deepCopy)(e))._id={_id:e._id,__v:e.__v},index_1.ResolveIOServer.getMongoManager().collection(t.versionCollection).replaceOne({_id:{_id:e._id,__v:e.__v}},n,{upsert:!0})),index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(t.collectionName),i(e)):i(null)},function(e){o.finish(),console.log(new Date,"Error Find One And Delete",t.collectionName,r,c,e),n(e)}),[2]})})})},r.prototype.findOneAndReplace=function(a,l,s,d,u){var e=this;return void 0===a&&(a={}),void 0===d&&(d=!1),void 0===u&&(u=!1),new Promise(function(r,c){return __awaiter(e,void 0,void 0,function(){var n,o,t,i=this;return __generator(this,function(e){return!this.checkSchema||u||(n=this.simplschema.newContext(),n.validate(l))?(o=new Date,this.timestamps&&(l.updatedAt=o),s&&s.upsert&&(l._id||(l._id=objectIdHexString()),this.useVersions&&(l.__v=0),this.timestamps)&&!l.createdAt&&(l.createdAt=o),t=new monitor_manager_1.MonitorMongo("findOneAndReplace",this.collectionName,JSON.stringify([a,l,s])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).findOneAndReplace(a,l,s).then(function(e){t.finish();var n;e?(i.createLogs&&!d&&log_collection_1.Logs.insertOne({_id:objectIdHexString(),type:"document",collection:i.collectionName,id_document:e._id,payload:(0,common_1.getBinarySize)(JSON.stringify([e,a,l,s]))<2e5?JSON.stringify([e,a,l,s],null,2):"Too Big",method:"findOneAndReplace",id_user:"",user:"",messageId:0,route:""}),i.useVersions&&((n=(0,common_1.deepCopy)(e))._id={_id:e._id,__v:e.__v},index_1.ResolveIOServer.getMongoManager().collection(i.versionCollection).replaceOne({_id:{_id:e._id,__v:e.__v}},n,{upsert:!0})),index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(i.collectionName),r(e)):r(null)},function(e){t.finish(),console.log(new Date,"Error Find One And Replace",i.collectionName,a,s,e),c(e)})):(console.log(new Date,this.collectionName,"Schema Errors - findOneAndReplace",n.validationErrors()),index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal.call(index_1.ResolveIOServer.getMainServer().getMethodManager(),"insertErrorLog","Schema Failed on findOneAndReplace - "+this.collectionName,[n.validationErrors(),l]),c(n.validationErrors())),[2]})})})},r.prototype.findOneAndUpdate=function(a,l,s,d,u){var e=this;return void 0===a&&(a={}),void 0===d&&(d=!1),void 0===u&&(u=!1),new Promise(function(r,c){return __awaiter(e,void 0,void 0,function(){var n,o,t,i=this;return __generator(this,function(e){return!this.checkSchema||u||(n=this.simplschema.newContext(),n.validate(l,{modifier:!0}))?(this.timestamps&&(o=new Date,l.$set?l.$set.updatedAt=o:l.$set={updatedAt:o}),s&&s.upsert&&(l.$setOnInsert?(l.$setOnInsert._id||(l.$setOnInsert._id=objectIdHexString()),this.timestamps&&(l.$setOnInsert.createdAt=new Date)):this.timestamps?l.$setOnInsert={_id:objectIdHexString(),createdAt:new Date}:l.$setOnInsert={_id:objectIdHexString()}),t=new monitor_manager_1.MonitorMongo("findOneAndUpdate",this.collectionName,JSON.stringify([a,l,s])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).findOneAndUpdate(a,l,s).then(function(e){t.finish();var n;e?(i.createLogs&&!d&&log_collection_1.Logs.insertOne({_id:objectIdHexString(),type:"document",collection:i.collectionName,id_document:e._id,payload:(0,common_1.getBinarySize)(JSON.stringify([e,a,l,s]))<2e5?JSON.stringify([e,a,l,s],null,2):"Too Big",method:"findOneAndUpdate",id_user:"",user:"",messageId:0,route:""}),i.useVersions&&((n=(0,common_1.deepCopy)(e))._id={_id:e._id,__v:e.__v},index_1.ResolveIOServer.getMongoManager().collection(i.versionCollection).replaceOne({_id:{_id:e._id,__v:e.__v}},n,{upsert:!0})),index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(i.collectionName),r(e)):r(null)},function(e){t.finish(),console.log(new Date,"Error Find One And Update",i.collectionName,a,s,e),c(e)})):(console.log(new Date,this.collectionName,"Schema Errors - findOneAndUpdate",n.validationErrors()),index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal.call(index_1.ResolveIOServer.getMainServer().getMethodManager(),"insertErrorLog","Schema Failed on findOneAndUpdate - "+this.collectionName,[n.validationErrors(),l]),c(n.validationErrors())),[2]})})})},r.prototype.indexes=function(i){var r=this;return new Promise(function(n,o){var t=new monitor_manager_1.MonitorMongo("indexes",r.collectionName,JSON.stringify([i]));index_1.ResolveIOServer.getMainDB().collection(r.collectionName,r.collectionOptions).indexes(i).then(function(e){t.finish(),n(e)},function(e){t.finish(),console.log(new Date,"Error Indexes",r.collectionName,i,e),o(e)})})},r.prototype.indexExists=function(i,r){var c=this;return new Promise(function(n,o){var t=new monitor_manager_1.MonitorMongo("indexExists",c.collectionName,JSON.stringify([i,r]));index_1.ResolveIOServer.getMainDB().collection(c.collectionName,c.collectionOptions).indexExists(i,r).then(function(e){t.finish(),n(e)},function(e){t.finish(),console.log(new Date,"Error Index Exists",c.collectionName,i,r,e),o(e)})})},r.prototype.insertMany=function(d,u,_,g,m){var e=this;return void 0===_&&(_=!1),void 0===g&&(g=!1),void 0===m&&(m=!1),new Promise(function(l,s){return __awaiter(e,void 0,void 0,function(){var o,n,t,i,r,c,a=this;return __generator(this,function(e){if(d.length){for(o=[],this.checkSchema&&!g&&d.forEach(function(e){var n=a.simplschema.newContext();n.validate(e)?o.push(!0):(console.log(new Date,a.collectionName,"Schema Errors - insertMany",n.validationErrors()),index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal.call(index_1.ResolveIOServer.getMainServer().getMethodManager(),"insertErrorLog","Schema Failed on insertMany - "+a.collectionName,[n.validationErrors(),e]),o.push(!1))}),n=this.checkSchema?d.filter(function(e,n){return o[n]}):d,t=0;t<n.length;t++)(i=n[t])._id||(i._id=objectIdHexString()),this.timestamps&&(r=new Date,i.createdAt=r,i.updatedAt=r),this.createLogs&&!_&&log_collection_1.Logs.insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:i._id,payload:(0,common_1.getBinarySize)(JSON.stringify([i,u]))<2e5?JSON.stringify([i,u],null,2):"Too Big",method:"insertMany",id_user:"",user:"",messageId:0,route:""});n.length&&(c=null,m||(c=new monitor_manager_1.MonitorMongo("insertMany",this.collectionName,JSON.stringify([n,u]))),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).insertMany(n,u).then(function(e){c&&c.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(a.collectionName),l(n)):s(e.acknowledged)},function(e){c&&c.finish(),console.log(new Date,"Error Insert Many",a.collectionName,n,u,e),s(e)}))}else l([]);return[2]})})})},r.prototype.insertOne=function(a,l,s,d){var e=this;return void 0===s&&(s=!1),void 0===d&&(d=!1),new Promise(function(r,c){return __awaiter(e,void 0,void 0,function(){var n,o,t,i=this;return __generator(this,function(e){return a._id||(a._id=objectIdHexString()),!this.checkSchema||d||(n=this.simplschema.newContext(),n.validate(a))?(this.timestamps&&(o=new Date,a.createdAt=o,a.updatedAt=o),this.createLogs&&!s&&log_collection_1.Logs.insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:a._id,payload:(0,common_1.getBinarySize)(JSON.stringify([a,l]))<2e5?JSON.stringify([a,l],null,2):"Too Big",method:"insertOne",id_user:"",user:"",messageId:0,route:""}),this.useVersions&&!a.hasOwnProperty("__v")&&(a.__v=0),t=new monitor_manager_1.MonitorMongo("insertOne",this.collectionName,JSON.stringify([a,l])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).insertOne(a,l).then(function(e){t.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(i.collectionName),r(a)):c(e.acknowledged)},function(e){t.finish(),console.log(new Date,"Error Insert One",i.collectionName,a,l,e),c(e)})):(console.log(new Date,this.collectionName,"Schema Errors - insertOne",n.validationErrors()),index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal.call(index_1.ResolveIOServer.getMainServer().getMethodManager(),"insertErrorLog","Schema Failed on insertOne - "+this.collectionName,[n.validationErrors(),a]),c(n.validationErrors())),[2]})})})},r.prototype.listIndexes=function(e){var n=new monitor_manager_1.MonitorMongo("listIndexes",this.collectionName,JSON.stringify([e])),e=index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).listIndexes(e);return e.on("close",function(e){return n.finish(),e}),e},r.prototype.rename=function(i,r){var c=this;return new Promise(function(n,o){var t=new monitor_manager_1.MonitorMongo("rename",c.collectionName,JSON.stringify([i,r]));index_1.ResolveIOServer.getMainDB().collection(c.collectionName,c.collectionOptions).rename(i,r).then(function(e){t.finish(),n(e)},function(e){t.finish(),console.log(new Date,"Error Rename",c.collectionName,i,r,e),o(e)})})},r.prototype.replaceOne=function(h,f,v,p,O,M){var e=this;return void 0===p&&(p=!1),void 0===O&&(O=!1),void 0===M&&(M=null),new Promise(function(g,m){return __awaiter(e,void 0,void 0,function(){var n,o,t,i,r,c,a,l,s,d,u,_=this;return __generator(this,function(e){switch(e.label){case 0:return!this.checkSchema||O||(o=this.simplschema.newContext(),o.validate(f))?(n=new Date,this.timestamps&&(f.updatedAt=n),this.useVersions?M?[3,2]:[4,this.findOne(h,null,!0)]:[3,8]):(console.log(new Date,this.collectionName,"Schema Errors - replaceOne",o.validationErrors()),index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal.call(index_1.ResolveIOServer.getMainServer().getMethodManager(),"insertErrorLog","Schema Failed on replaceOne - "+this.collectionName,[o.validationErrors(),f]),m(o.validationErrors()),[2]);case 1:M=e.sent(),e.label=2;case 2:return M?(this.timestamps&&!f.createdAt&&M.createdAt&&(f.createdAt=M.createdAt),M.__v!==f.__v?[3,3]:(f.__v+=1,(o=(0,common_1.deepCopy)(M))._id={_id:M._id,__v:M.__v},index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).replaceOne({_id:{_id:M._id,__v:M.__v}},o,{upsert:!0}),4<=M.__v&&index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).deleteMany({$and:[{"_id._id":M._id},{"_id.__v":{$lt:M.__v-4}}]}),this.createLogs&&!p&&log_collection_1.Logs.insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:M._id,payload:(0,common_1.getBinarySize)(JSON.stringify([M,h,f,v]))<2e5?JSON.stringify([M,h,f,v],null,2):"Too Big",method:"replaceOne",id_user:"",user:"",messageId:0,route:""}),t=new monitor_manager_1.MonitorMongo("replaceOne",this.collectionName,JSON.stringify([h,f,v])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).replaceOne(h,f,v).then(function(e){t.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(_.collectionName),g(e.modifiedCount)):m(e.acknowledged)},function(e){t.finish(),console.log(new Date,"Error Replace One",_.collectionName,h,f,v,e),m(e)}),[3,5])):[3,6];case 3:return console.log("invalid version - "+this.collectionName,M.__v,f.__v),[4,index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).findOne({_id:{_id:M._id,__v:f.__v}},null,!0)];case 4:(i=e.sent())?(r=M._id,c=M.__v,(a=(0,common_1.getMongoMergeUpdatedDoc)(f,M,i))._id=r,a.__v=c+1,this.createLogs&&!p&&log_collection_1.Logs.insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:r,payload:(0,common_1.getBinarySize)(JSON.stringify(["invalidVersion - merge",M,h,a,v]))<2e5?JSON.stringify(["invalidVersion - merge",M,h,a,v],null,2):"Too Big",method:"replaceOne",id_user:"",user:"",messageId:0,route:""}),l=new monitor_manager_1.MonitorMongo("replaceOne",this.collectionName,JSON.stringify([h,a,v])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).replaceOne(h,a,v).then(function(e){l.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(_.collectionName),g(e.modifiedCount)):m(e.acknowledged)},function(e){l.finish(),console.log(new Date,"Error Replace One",_.collectionName,h,a,v,e),m(e)})):m("Invalid Version And Could Not Find History - DB: "+M.__v+", Trying to update with :"+f.__v),e.label=5;case 5:return[3,7];case 6:v&&v.upsert?(this.timestamps&&(f.createdAt=n),f._id||(f._id=objectIdHexString()),f.__v=0,this.createLogs&&!p&&log_collection_1.Logs.insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:f._id,payload:(0,common_1.getBinarySize)(JSON.stringify(["upsert",h,f,v]))<2e5?JSON.stringify(["upsert",h,f,v],null,2):"Too Big",method:"replaceOne",id_user:"",user:"",messageId:0,route:""}),s=new monitor_manager_1.MonitorMongo("replaceOne",this.collectionName,JSON.stringify([h,f,v])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).replaceOne(h,f,v).then(function(e){s.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(_.collectionName),g(e.modifiedCount)):m(e.acknowledged)},function(e){s.finish(),console.log(new Date,"Error Replace One",_.collectionName,h,f,v,e),m(e)})):m("No Document"),e.label=7;case 7:return[3,9];case 8:v&&v.upsert&&(this.timestamps&&!f.createdAt&&(f.createdAt=n),f._id||(f._id=objectIdHexString()),f.__v=0),this.createLogs&&!p?(v?v.returnDocument="before":v={returnDocument:"before"},d=new monitor_manager_1.MonitorMongo("findOneAndReplace",this.collectionName,JSON.stringify([h,f,v])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).findOneAndReplace(h,f,v).then(function(e){d.finish();e?log_collection_1.Logs.insertOne({_id:objectIdHexString(),type:"document",collection:_.collectionName,id_document:e._id,payload:(0,common_1.getBinarySize)(JSON.stringify([e,h,f,v]))<2e5?JSON.stringify([e,h,f,v],null,2):"Too Big",method:"replaceOne",id_user:"",user:"",messageId:0,route:""}):log_collection_1.Logs.insertOne({_id:objectIdHexString(),type:"document",collection:_.collectionName,id_document:f._id,payload:(0,common_1.getBinarySize)(JSON.stringify(["upsert",h,f,v]))<2e5?JSON.stringify(["upsert",h,f,v],null,2):"Too Big",method:"replaceOne",id_user:"",user:"",messageId:0,route:""}),index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(_.collectionName),g(1)},function(e){d.finish(),console.log(new Date,"Error Find One And Replace",_.collectionName,h,f,v,e),m(e)})):(u=new monitor_manager_1.MonitorMongo("replaceOne",this.collectionName,JSON.stringify([h,f,v])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).replaceOne(h,f,v).then(function(e){u.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(_.collectionName),g(e.modifiedCount)):m(e.acknowledged)},function(e){u.finish(),console.log(new Date,"Error Replace One",_.collectionName,h,f,v,e),m(e)})),e.label=9;case 9:return[2]}})})})},r.prototype.updateMany=function(d,u,_,g,m,h){var e=this;return void 0===g&&(g=!1),void 0===m&&(m=!1),void 0===h&&(h=!1),new Promise(function(l,s){return __awaiter(e,void 0,void 0,function(){var n,o,t,i,r,c,a=this;return __generator(this,function(e){switch(e.label){case 0:return u.$inc&&"{}"!==JSON.stringify(u.$inc)||u.$set&&"{}"!==JSON.stringify(u.$set)||u.$setOnInsert&&"{}"!==JSON.stringify(u.$setOnInsert)||u.$unset&&"{}"!==JSON.stringify(u.$unset)?(this.timestamps&&(n=new Date,u.$set?u.$set.updatedAt=n:u.$set={updatedAt:n}),!this.checkSchema||m||(n=this.simplschema.newContext(),n.validate(u,{modifier:!0}))?this.useVersions&&!h||this.createLogs&&!g?[4,this.find(d)]:[3,2]:(console.log(new Date,this.collectionName,"Schema Errors - updateMany",n.validationErrors()),index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal.call(index_1.ResolveIOServer.getMainServer().getMethodManager(),"insertErrorLog","Schema Failed on updateMany - "+this.collectionName,[n.validationErrors(),u]),s(n.validationErrors()),[2])):(l(1),[2]);case 1:for(o=e.sent(),t=0;t<o.length;t++)i=o[t],this.createLogs&&!g&&log_collection_1.Logs.insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:i._id,payload:(0,common_1.getBinarySize)(JSON.stringify([i,d,u,_]))<2e5?JSON.stringify([i,d,u,_],null,2):"Too Big",method:"updateMany",id_user:"",user:"",messageId:0,route:""}),this.useVersions&&((r=(0,common_1.deepCopy)(i))._id={_id:i._id,__v:i.__v},index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).replaceOne({_id:{_id:i._id,__v:i.__v}},r,{upsert:!0}),4<=i.__v&&index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).deleteMany({$and:[{"_id._id":i._id},{"_id.__v":{$lt:i.__v-4}}]}),objectContainsPropertyDeep(u,"__v")||(u.$inc?u.$inc.__v||(u.$inc.__v=1):u.$inc={__v:1}));e.label=2;case 2:return c=new monitor_manager_1.MonitorMongo("updateMany",this.collectionName,JSON.stringify([d,u,_])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).updateMany(d,u,_).then(function(e){c.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(a.collectionName),l(e.modifiedCount)):s(e.acknowledged)},function(e){c.finish(),console.log(new Date,"Error Update Many",a.collectionName,d,u,_,e),s(e)}),[2]}})})})},r.prototype.updateOne=function(d,u,_,g,m){var e=this;return void 0===g&&(g=!1),void 0===m&&(m=!1),new Promise(function(l,s){return __awaiter(e,void 0,void 0,function(){var n,o,t,i,r,c,a=this;return __generator(this,function(e){switch(e.label){case 0:return!this.checkSchema||m||(o=this.simplschema.newContext(),o.validate(u,{modifier:!0}))?u.$inc&&"{}"!==JSON.stringify(u.$inc)||u.$set&&"{}"!==JSON.stringify(u.$set)||u.$setOnInsert&&"{}"!==JSON.stringify(u.$setOnInsert)||u.$unset&&"{}"!==JSON.stringify(u.$unset)?(n=new Date,this.timestamps&&(u.$set?u.$set.updatedAt=n:u.$set={updatedAt:n}),this.useVersions?[4,this.findOne(d,null,!0)]:[3,2]):(l(1),[2]):(console.log(new Date,this.collectionName,"Schema Errors - updateOne",o.validationErrors()),index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal.call(index_1.ResolveIOServer.getMainServer().getMethodManager(),"insertErrorLog","Schema Failed on updateOne - "+this.collectionName,[o.validationErrors(),u]),s(o.validationErrors()),[2]);case 1:return(n=e.sent())?(this.createLogs&&!g&&log_collection_1.Logs.insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:n._id,payload:(0,common_1.getBinarySize)(JSON.stringify([n,d,u,_]))<2e5?JSON.stringify([n,d,u,_],null,2):"Too Big",method:"updateOne",id_user:"",user:"",messageId:0,route:""}),(o=(0,common_1.deepCopy)(n))._id={_id:n._id,__v:n.__v},index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).replaceOne({_id:{_id:n._id,__v:n.__v}},o,{upsert:!0}),4<=n.__v&&index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).deleteMany({$and:[{"_id._id":n._id},{"_id.__v":{$lt:n.__v-4}}]}),objectContainsPropertyDeep(u,"__v")||(u.$inc?u.$inc.__v||(u.$inc.__v=1):u.$inc={__v:1}),t=new monitor_manager_1.MonitorMongo("updateOne",this.collectionName,JSON.stringify([d,u,_])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).updateOne(d,u,_).then(function(e){t.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(a.collectionName),l(e.modifiedCount)):s(e.acknowledged)},function(e){t.finish(),console.log(new Date,"Error Update One",a.collectionName,d,u,_,e),s(e)})):_&&_.upsert?(u.$setOnInsert?(u.$setOnInsert._id||(u.$setOnInsert._id=objectIdHexString()),this.timestamps&&(u.$setOnInsert.createdAt=new Date)):this.timestamps?u.$setOnInsert={_id:objectIdHexString(),__v:0,createdAt:new Date}:u.$setOnInsert={_id:objectIdHexString(),__v:0},this.createLogs&&!g&&log_collection_1.Logs.insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:u.$setOnInsert._id,payload:(0,common_1.getBinarySize)(JSON.stringify(["upsert",d,u,_]))<2e5?JSON.stringify(["upsert",d,u,_],null,2):"Too Big",method:"updateOne",id_user:"",user:"",messageId:0,route:""}),i=new monitor_manager_1.MonitorMongo("updateOne",this.collectionName,JSON.stringify([d,u,_])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).updateOne(d,u,_).then(function(e){i.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(a.collectionName),l(e.modifiedCount)):s(e.acknowledged)},function(e){i.finish(),console.log(new Date,"Error Update One",a.collectionName,d,u,_,e),s(e)})):s("No Document"),[3,3];case 2:_&&_.upsert&&(u.$setOnInsert?(u.$setOnInsert._id||(u.$setOnInsert._id=objectIdHexString()),this.timestamps&&(u.$setOnInsert.createdAt=new Date)):this.timestamps?u.$setOnInsert={_id:objectIdHexString(),createdAt:new Date}:u.$setOnInsert={_id:objectIdHexString()}),this.createLogs&&!g?(_?_.returnDocument="before":_={returnDocument:"before"},r=new monitor_manager_1.MonitorMongo("findOneAndUpdate",this.collectionName,JSON.stringify([d,u,_])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).findOneAndUpdate(d,u,_).then(function(e){r.finish();var n=e.value;n?(log_collection_1.Logs.insertOne({_id:objectIdHexString(),type:"document",collection:a.collectionName,id_document:n._id,payload:(0,common_1.getBinarySize)(JSON.stringify([n,d,u,_]))<2e5?JSON.stringify([n,d,u,_],null,2):"Too Big",method:"updateOne",id_user:"",user:"",messageId:0,route:""}),l(e.ok)):u.$setOnInsert?(log_collection_1.Logs.insertOne({_id:objectIdHexString(),type:"document",collection:a.collectionName,id_document:u.$setOnInsert._id,payload:(0,common_1.getBinarySize)(JSON.stringify(["upsert",d,u,_]))<2e5?JSON.stringify(["upsert",d,u,_],null,2):"Too Big",method:"updateOne",id_user:"",user:"",messageId:0,route:""}),index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(a.collectionName),l(e.ok)):l(0)},function(e){r.finish(),console.log(new Date,"Error Find One And Update",a.collectionName,d,u,_,e),s(e)})):(c=new monitor_manager_1.MonitorMongo("updateOne",this.collectionName,JSON.stringify([d,u,_])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).updateOne(d,u,_).then(function(e){c.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(a.collectionName),l(e.modifiedCount)):s(e.acknowledged)},function(e){c.finish(),console.log(new Date,"Error Update One",a.collectionName,d,u,_,e),s(e)})),e.label=3;case 3:return[2]}})})})},r.prototype.watchCollection=function(e,n){return void 0===e&&(e=[]),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).watch(e,n)},r.prototype.watchCollectionWithAggregate=function(e,n){return void 0===e&&(e=[]),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).watch(e,n)},(e=r).indexQueue=async_1.default.queue(function(n,u){return __awaiter(void 0,void 0,void 0,function(){var i,r,c,a,l,s,d;return __generator(e,function(e){switch(e.label){case 0:return(i=n.action,r=n.collection,c=n.specs,a=n.options,l=index_1.ResolveIOServer.getMainDB().collection(r.collectionName,r.collectionOptions))?(s=new monitor_manager_1.MonitorMongo(i,r.collectionName,JSON.stringify([c,a])),[4,(d=function(){return __awaiter(void 0,void 0,void 0,function(){var n,o,t;return __generator(this,function(e){switch(e.label){case 0:return e.trys.push([0,2,,9]),[4,l[i].apply(l,__spreadArray(__spreadArray([],c,!1),[a],!1))];case 1:return o=e.sent(),s.finish(),u(null,o),[3,9];case 2:if(85!==(n=e.sent()).code&&!n.message.includes("IndexOptionsConflict"))return[3,8];e.label=3;case 3:return(e.trys.push([3,7,,8]),o=r.extractIndexNameFromError(n.message))?[4,l.dropIndex(o)]:[3,6];case 4:return e.sent(),[4,d()];case 5:return[2,e.sent()];case 6:return[3,8];case 7:return t=e.sent(),u(t),[3,8];case 8:return s.finish(),u(n),[3,9];case 9:return[2]}})})})()]):[2,u(new Error("Collection ".concat(r.collectionName," not found")))];case 1:return e.sent(),[2]}})})},1),r}()),MongoManagerUserCollection=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return __extends(n,e),n.prototype.authenticate=function(c,o){var e=this;return new Promise(function(i,r){return __awaiter(e,void 0,void 0,function(){var n,t=this;return __generator(this,function(e){switch(e.label){case 0:return(n=Math.pow(100,Math.log(c.attempts+1)),n=n<3e5?n:3e5,c.last)?Date.now()-c.last.getTime()<n?(c.last=new Date,[4,user_collection_1.Users.updateOne({_id:c._id},{$set:{last:c.last}})]):[3,2]:[3,3];case 1:return e.sent(),i({data:null,error:"Attempt Too Soon"}),[2];case 2:return[3,4];case 3:c.last=new Date,e.label=4;case 4:return 5<=c.attempts?i({data:null,error:"Too Many Attempts"}):c.salt?pbkdf2(o,c.salt,{iterations:25e3,keylen:512,digestAlgorithm:"sha256"},function(n,o){return __awaiter(t,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return n?[2,r(n)]:scmp(o,Buffer.from(c.hash,"hex"))?(c.last=new Date,c.attempts=0,[4,user_collection_1.Users.updateOne({_id:c._id},{$set:{last:c.last,attempts:c.attempts}})]):[3,2];case 1:return e.sent(),i({data:c,error:""}),[3,4];case 2:return c.last=new Date,c.attempts=c.attempts+1,[4,user_collection_1.Users.updateOne({_id:c._id},{$set:{last:c.last,attempts:c.attempts}})];case 3:e.sent(),5<=c.attempts?i({data:null,error:"Too Many Attempts"}):i({data:null,error:"Invalid Username And Password"}),e.label=4;case 4:return[2]}})})}):i({data:null,error:"No Salt Value Stored"}),[2]}})})})},n.prototype.serializeUser=function(){return function(e,n){n(null,e.username)}},n.prototype.deserializeUser=function(){return function(e,n){user_collection_1.Users.findOne({username:e}).then(function(e){n(null,e)},function(e){n(e,null)})}},n.prototype.setPassword=function(r,c){var e=this;return new Promise(function(t,i){return __awaiter(e,void 0,void 0,function(){var n,o;return __generator(this,function(e){switch(e.label){case 0:return r?[3,1]:(i("No User"),[3,5]);case 1:return c?[3,2]:(i("No Password"),[3,5]);case 2:return[4,randomBytes(32)];case 3:return n=e.sent(),n=n.toString("hex"),[4,pbkdf2Promisified(c,n,{iterations:25e3,keylen:512,digestAlgorithm:"sha256"})];case 4:o=e.sent(),o=Buffer.from(o,"binary").toString("hex"),user_collection_1.Users.updateOne({_id:r._id},{$set:{hash:o,salt:n,services:{},attempts:0}}).then(function(e){return t(e)},function(e){return i(e)}),e.label=5;case 5:return[2]}})})})},n.prototype.changePassword=function(i,r,c){var e=this;return new Promise(function(o,t){return __awaiter(e,void 0,void 0,function(){var n;return __generator(this,function(e){switch(e.label){case 0:return i?[3,1]:(t("Missing User"),[3,4]);case 1:return r&&c?[3,2]:(t("Missing Password"),[3,4]);case 2:return[4,this.authenticate(i,r)];case 3:(n=e.sent()).data?this.setPassword(i,c).then(function(e){return o(e)},function(e){return t(e)}):t(n.error),e.label=4;case 4:return[2]}})})})},n.prototype.register=function(t,i){var e=this;return new Promise(function(n,o){return __awaiter(e,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return t.username?[3,1]:(o("Missing Username"),[3,5]);case 1:return[4,user_collection_1.Users.findOne({username:t.username})];case 2:return e.sent()?(o("Username Exists"),[3,5]):[3,3];case 3:return[4,user_collection_1.Users.findOne({email:t.email})];case 4:e.sent()?o("Email Exists"):(t.setPassword(i),n(t)),e.label=5;case 5:return[2]}})})})},n.prototype.resetAttempts=function(e){return user_collection_1.Users.updateOne({_id:e._id},{$set:{attempts:0}})},n}(exports.MongoManagerCollection=MongoManagerCollection);function objectIdHexString(){return(new mongodb_1.ObjectId).toHexString()}function pbkdf2(e,n,o,t){crypto.pbkdf2(e,n,o.iterations,o.keylen,o.digestAlgorithm,t)}function pbkdf2Promisified(e,n,i){return new Promise(function(o,t){return pbkdf2(e,n,i,function(e,n){return e?t(e):o(n)})})}function randomBytes(e){return new Promise(function(o,t){return crypto.randomBytes(e,function(e,n){return e?t(e):o(n)})})}function objectContainsPropertyDeep(e,n){var o=Object.keys(e);if(o.some(function(e){return e===n}))return!0;for(var t=0;t<o.length;t++){var i=o[t];if(e[i]&&"object"==typeof e[i]&&objectContainsPropertyDeep(e[i],n))return!0}return!1}exports.MongoManagerUserCollection=MongoManagerUserCollection,exports.objectIdHexString=objectIdHexString;
2260
2
  //# sourceMappingURL=mongo.manager.js.map