UNPKG

36.3 kBJavaScriptView Raw
1"use strict";
2const Q = require('q');
3const entity_change_1 = require('../core/enums/entity-change');
4const model_entity_1 = require('../core/dynamic/model-entity');
5const Enumerable = require('linq');
6const winstonLog_1 = require('../logging/winstonLog');
7const mongooseHelper = require('./mongoose-model-helper');
8const CoreUtils = require("../core/utils");
9const constants_1 = require('../core/constants');
10const Utils = require('./utils');
11const utils_1 = require("../core/metadata/utils");
12const decorators_1 = require('../core/constants/decorators');
13const dynamic_schema_1 = require('./dynamic-schema');
14const instance_service_1 = require('../core/services/instance-service');
15/**
16 * Iterate through objArr and check if any child object need to be added. If yes, then add those child objects.
17 * Bulk create these updated objects.
18 * Usage - Post multiple objects parallely
19 * @param model
20 * @param objArr
21 */
22function bulkPost(model, objArr, batchSize) {
23 if (!objArr) {
24 return Q.when([]);
25 }
26 if (objArr && objArr.length <= 0) {
27 return Q.when([]);
28 }
29 //console.log("bulkPost " + model.modelName);
30 mongooseHelper.updateWriteCount();
31 var addChildModel = [];
32 // create all cloned models
33 var clonedModels = [];
34 let transientProps = mongooseHelper.getAllTransientProps(model);
35 Enumerable.from(objArr).forEach(obj => {
36 var cloneObj = mongooseHelper.removeGivenTransientProperties(model, obj, transientProps);
37 cloneObj[constants_1.ConstantKeys.TempId] = cloneObj._id ? cloneObj._id : Utils.autogenerateIds(model);
38 clonedModels.push(cloneObj);
39 });
40 return mongooseHelper.addChildModelToParent(model, clonedModels)
41 .then(result => {
42 // autogenerate ids of all the objects
43 //Enumerable.from(clonedModels).forEach(clonedObj => {
44 // try {
45 // mongooseHelper.autogenerateIdsForAutoFields(model, clonedObj);
46 // //Object.assign(obj, clonedObj);
47 // } catch (ex) {
48 // winstonLog.logError(`Error in bulkPost ${ex}`);
49 // return Q.reject(ex);
50 // }
51 //});
52 var asyncCalls = [];
53 if (!batchSize)
54 batchSize = 1000;
55 for (let curCount = 0; curCount < clonedModels.length; curCount += batchSize) {
56 asyncCalls.push(executeBulk(model, clonedModels.slice(curCount, curCount + batchSize)));
57 }
58 return Q.allSettled(asyncCalls).then(suces => {
59 let values = [];
60 values = suces.map(x => x.value).reduce((prev, current) => {
61 return prev.concat(current);
62 });
63 //console.log("bulkPost end" + model.modelName);
64 return values;
65 }).catch(er => {
66 winstonLog_1.winstonLog.logError(`Error in bulkPost ${model.modelName}: ${er}`);
67 throw er;
68 });
69 });
70}
71exports.bulkPost = bulkPost;
72function executeBulk(model, arrayOfDbModels) {
73 //console.log("start executeBulk post", model.modelName);
74 let executeBulkPost = {};
75 arrayOfDbModels.forEach(x => {
76 if (x[constants_1.ConstantKeys.TempId]) {
77 x._id = x[constants_1.ConstantKeys.TempId];
78 delete x[constants_1.ConstantKeys.TempId];
79 }
80 mongooseHelper.setUniqueIdFromShard(x);
81 mongooseHelper.setShardCondition(model, x);
82 let newModel = mongooseHelper.getNewModelFromObject(model, x);
83 if (!executeBulkPost[newModel.modelName]) {
84 executeBulkPost[newModel.modelName] = { objs: [], model: newModel };
85 }
86 executeBulkPost[newModel.modelName].objs.push(x);
87 if (!dynamic_schema_1._arrayPropListSchema[model.modelName]) {
88 return;
89 }
90 // assign empty array for not defined properties
91 dynamic_schema_1._arrayPropListSchema[model.modelName].forEach(prop => {
92 if (!x[prop]) {
93 x[prop] = [];
94 }
95 });
96 });
97 let asycnCalls = [];
98 Object.keys(executeBulkPost).forEach(x => {
99 asycnCalls.push(Q.nbind(executeBulkPost[x].model.collection.insertMany, executeBulkPost[x].model.collection)(executeBulkPost[x].objs));
100 });
101 //console.log("empty array executeBulk ", model.modelName);
102 return Q.allSettled(asycnCalls).then(result => {
103 //console.log("end executeBulk post", model.modelName);
104 let values = [];
105 values = result.map(x => x.value.ops).reduce((prev, current) => {
106 return prev.concat(current);
107 });
108 return values;
109 }).catch(err => {
110 throw err;
111 });
112}
113/**
114 * Iterate through objArr and call put for these
115 * Usage - Update multiple object sequentially
116 * @param model
117 * @param objArr
118 */
119function bulkPut(model, objArr, batchSize, donotLoadChilds) {
120 if (!objArr || !objArr.length)
121 return Q.when([]);
122 //console.log("bulkPut " + model.modelName);
123 mongooseHelper.updateWriteCount();
124 var asyncCalls = [];
125 var length = objArr.length;
126 var ids = objArr.map(x => x._id);
127 var bulk = model.collection.initializeUnorderedBulkOp();
128 var asyncCalls = [];
129 if (!batchSize) {
130 asyncCalls.push(executeBulkPut(model, objArr, donotLoadChilds));
131 }
132 else {
133 for (let curCount = 0; curCount < objArr.length; curCount += batchSize) {
134 asyncCalls.push(executeBulkPut(model, objArr.slice(curCount, curCount + batchSize), donotLoadChilds));
135 }
136 }
137 return Q.allSettled(asyncCalls).then(suces => {
138 let values = [];
139 values = suces.map(x => x.value).reduce((prev, current) => {
140 return prev.concat(current);
141 });
142 //console.log("bulkPut end" + model.modelName);
143 return values;
144 }).catch(er => {
145 winstonLog_1.winstonLog.logError(`Error in bulkPut ${model.modelName}: ${er}`);
146 throw er;
147 });
148}
149exports.bulkPut = bulkPut;
150function executeBulkPut(model, objArr, donotLoadChilds) {
151 let length = objArr.length;
152 var asyncCalls = [];
153 let fullyLoaded = objArr && objArr.length > 0 && objArr[0][constants_1.ConstantKeys.FullyLoaded];
154 let updateParentRequired = [];
155 var objectIds = [];
156 //console.log("bulkPut addChildModelToParent child start" + model.modelName);
157 let allUpdateProps = [];
158 return mongooseHelper.addChildModelToParent(model, objArr).then(r => {
159 //console.log("bulkPut addChildModelToParent child end" + model.modelName);
160 let transientProps = mongooseHelper.getAllTransientProps(model);
161 var metaArr = CoreUtils.getAllRelationsForTargetInternal(model_entity_1.getEntity(model.modelName));
162 let isRelationsExist = false;
163 if (metaArr && metaArr.length) {
164 isRelationsExist = true;
165 }
166 //let updatePropsReq = !fullyLoaded || isRelationsExist;
167 // check if not relationship present in the docs then do not call updateProps
168 //
169 let allBulkExecute = {};
170 for (let i = 0; i < objArr.length; i++) {
171 let result = objArr[i];
172 let newModel = mongooseHelper.getNewModelFromObject(model, result);
173 var objectId = Utils.getCastObjectId(newModel, result._id);
174 objectIds.push(objectId);
175 let id = result._id;
176 let parent = result.parent;
177 if (!allBulkExecute[newModel.modelName]) {
178 allBulkExecute[newModel.modelName] = newModel.collection.initializeUnorderedBulkOp();
179 }
180 let bulk = allBulkExecute[newModel.modelName];
181 delete result._id;
182 delete result[constants_1.ConstantKeys.FullyLoaded];
183 for (let prop in transientProps) {
184 delete result[transientProps[prop].propertyKey];
185 }
186 var updatedProps;
187 updatedProps = Utils.getUpdatedProps(result, entity_change_1.EntityChange.put);
188 // //console.log("update props", updatedProps);
189 delete result.__dbEntity;
190 // update only modified objects
191 if (Object.keys(updatedProps).length === 0) {
192 continue;
193 }
194 updateParentRequired.push(objectId);
195 //if (updatePropsReq) {
196 // updatedProps = Utils.getUpdatedProps(result, EntityChange.put);
197 // // update only modified objects
198 // if (Object.keys(updatedProps).length === 0) {
199 // continue;
200 // }
201 //}
202 let isDecoratorPresent = isDecoratorApplied(model, decorators_1.Decorators.OPTIMISTICLOCK, "put");
203 let query = { _id: objectId };
204 if (isDecoratorPresent === true) {
205 updatedProps["$set"] && delete updatedProps["$set"]["__v"];
206 updatedProps["$inc"] = { '__v': 1 };
207 query["__v"] = result["__v"];
208 }
209 bulk.find(mongooseHelper.setShardCondition(model, { _id: objectId })).update(updatedProps);
210 }
211 let asyncCalls = [];
212 //let promBulkUpdate = Q.when({});
213 //console.log("bulkPut bulk.execute start" + model.modelName);
214 if (updateParentRequired.length > 0) {
215 Object.keys(allBulkExecute).forEach(x => {
216 let bulk = allBulkExecute[x];
217 asyncCalls.push(Q.nbind(bulk.execute, bulk)());
218 });
219 }
220 return Q.allSettled(asyncCalls).then(result => {
221 //return promBulkUpdate.then(result => {
222 //console.log("bulkPut bulk.execute end" + model.modelName);
223 // update parent
224 let repo = model_entity_1.repoFromModel[model.modelName];
225 let prom;
226 if (fullyLoaded) {
227 // remove eagerloading propeties because it will be used for updating parent
228 // validate that no one have tampered the new persistent entity
229 prom = Q.when(objArr);
230 objectIds.forEach((id, index) => {
231 objArr[index]['_id'] = id;
232 });
233 }
234 else {
235 prom = findMany(model, objectIds);
236 }
237 return prom.then((objects) => {
238 let updateParentProm = Q.when([]);
239 // if (updateParentRequired.length > 0) {
240 // let updateObject = [];
241 // updateParentRequired.forEach(x => {
242 // updateObject.push(objects.find(obj => obj._id.toString() == x));
243 // });
244 // updateParentProm = mongooseHelper.updateParent(model, updateObject);
245 // }
246 if (updateParentRequired.length > 0) {
247 let updateObject = [];
248 let newObjectsMap = {};
249 objects.forEach(x => {
250 newObjectsMap[x._id.toString()] = x;
251 });
252 updateParentRequired.forEach(x => {
253 if (newObjectsMap[x]) {
254 updateObject.push(newObjectsMap[x]);
255 }
256 });
257 updateParentProm = mongooseHelper.updateParent(model, updateObject);
258 }
259 return updateParentProm.then(res => {
260 //console.log("bulkPut updateParent start" + model.modelName);
261 if (donotLoadChilds === true) {
262 return Q.when(objects);
263 }
264 return mongooseHelper.fetchEagerLoadingProperties(model, objects).then(resultObject => {
265 return resultObject;
266 });
267 });
268 });
269 });
270 }).catch(error => {
271 winstonLog_1.winstonLog.logError(`Error in executeBulkPut ${model.modelName}: ${error}`);
272 return Q.reject(error);
273 });
274}
275/**
276 * Iterate through objArr and call put for these
277 * Usage - Update multiple object sequentially
278 * @param model
279 * @param objArr
280 */
281function bulkPatch(model, objArr) {
282 if (!objArr || !objArr.length)
283 return Q.when([]);
284 //console.log("bulkPatch " + model.modelName);
285 mongooseHelper.updateWriteCount();
286 var asyncCalls = [];
287 var length = objArr.length;
288 var ids = objArr.map(x => x._id);
289 var asyncCalls = [];
290 return mongooseHelper.addChildModelToParent(model, objArr).then(x => {
291 let transientProps = mongooseHelper.getAllTransientProps(model);
292 let jsonProps = mongooseHelper.getEmbeddedPropWithFlat(model).map(x => x.propertyKey);
293 //it has to be group by
294 let allBulkExecute = {};
295 objArr.forEach(result => {
296 var objectId = Utils.getCastObjectId(model, result._id);
297 let newModel = mongooseHelper.getNewModelFromObject(model, result);
298 if (!allBulkExecute[newModel.modelName]) {
299 allBulkExecute[newModel.modelName] = newModel.collection.initializeUnorderedBulkOp();
300 }
301 let bulk = allBulkExecute[newModel.modelName];
302 delete result._id;
303 for (let prop in transientProps) {
304 delete result[transientProps[prop].propertyKey];
305 }
306 var updatedProps = Utils.getUpdatedProps(result, entity_change_1.EntityChange.patch, jsonProps);
307 let isDecoratorPresent = isDecoratorApplied(model, decorators_1.Decorators.OPTIMISTICLOCK, "patch");
308 let query = { _id: objectId };
309 if (isDecoratorPresent === true) {
310 updatedProps["$set"] && delete updatedProps["$set"]["__v"];
311 updatedProps["$inc"] = { '__v': 1 };
312 query["__v"] = result["__v"];
313 }
314 bulk.find(mongooseHelper.setShardCondition(model, query)).update(updatedProps);
315 });
316 let asyncCalls = [];
317 Object.keys(allBulkExecute).forEach(x => {
318 let bulk = allBulkExecute[x];
319 asyncCalls.push(Q.nbind(bulk.execute, bulk)());
320 });
321 return Q.allSettled(asyncCalls).then(result => {
322 // update parent
323 return findMany(model, ids).then((objects) => {
324 return mongooseHelper.updateParent(model, objects).then(res => {
325 return mongooseHelper.fetchEagerLoadingProperties(model, objects).then(resultObject => {
326 //console.log("bulkPatch end" + model.modelName);
327 return resultObject;
328 });
329 });
330 });
331 }).catch(error => {
332 winstonLog_1.winstonLog.logError(`Error in bulkPatch ${model.modelName}: ${error}`);
333 return Q.reject(error);
334 });
335 });
336}
337exports.bulkPatch = bulkPatch;
338/**
339 * Bulk update objects. Find updated objects, and update the parent docs
340 * Usage - Update multiple objects parallely with same porperty set
341 * @param model
342 * @param objIds
343 * @param obj
344 */
345function bulkPutMany(model, objIds, obj) {
346 if (!objIds || !objIds.length)
347 return Q.when([]);
348 //console.log("bulkPutMany " + model.modelName);
349 mongooseHelper.updateWriteCount();
350 delete obj._id;
351 let clonedObj = mongooseHelper.removeTransientProperties(model, obj);
352 // First update the any embedded property and then update the model
353 var cond = {};
354 cond['_id'] = {
355 $in: objIds
356 };
357 cond = mongooseHelper.setShardCondition(model, cond);
358 var updatedProps = Utils.getUpdatedProps(clonedObj, entity_change_1.EntityChange.put);
359 let newModels = mongooseHelper.getAllShardModelsFromIds(model, objIds);
360 let asyncCalls = [];
361 Object.keys(newModels).forEach(x => {
362 asyncCalls.push(Q.nbind(newModels[x].update, newModels[x])(cond, updatedProps, { multi: true }));
363 });
364 return Q.allSettled(asyncCalls)
365 .then(result => {
366 let allReferencingEntities = CoreUtils.getAllRelationsForTarget(model_entity_1.getEntity(model.modelName));
367 let ref = allReferencingEntities.find((x) => x.params && x.params.embedded);
368 if (ref) {
369 return findMany(model, objIds).then((objects) => {
370 return mongooseHelper.updateParent(model, objects).then(res => {
371 //console.log("bulkPutMany end" + model.modelName);
372 return objects;
373 });
374 });
375 }
376 else {
377 //console.log("bulkPutMany end" + model.modelName);
378 return result;
379 }
380 }).catch(error => {
381 winstonLog_1.winstonLog.logError(`Error in bulkPutMany ${model.modelName}: ${error}`);
382 return Q.reject(error);
383 });
384}
385exports.bulkPutMany = bulkPutMany;
386/**
387 * Usage - Find all the objects
388 * @param model
389 */
390function findAll(model) {
391 //console.log("findAll " + model.modelName);
392 return model.find(mongooseHelper.setShardCondition(model, {})).lean().then(result => {
393 //console.log("findAll end" + model.modelName);
394 return result;
395 }).catch(error => {
396 winstonLog_1.winstonLog.logError(`Error in findAll ${model.modelName}: ${error}`);
397 return Q.reject(error);
398 });
399}
400exports.findAll = findAll;
401/**
402 * Query collection and then populate child objects with relationship
403 * Usage - Search object with given condition
404 * @param model
405 * @param query
406 */
407function countWhere(model, query) {
408 if (Object.keys(query).length == 0) {
409 return Q.nbind(model.collection.stats, model.collection)().then((result) => {
410 return Q.resolve(result.count);
411 });
412 }
413 let queryObj = model.find(mongooseHelper.setShardCondition(model, query)).count();
414 //winstonLog.logInfo(`findWhere query is ${query}`);
415 return Q.nbind(queryObj.exec, queryObj)()
416 .then(result => {
417 // update embedded property, if any
418 return Q.resolve(result);
419 }).catch(error => {
420 winstonLog_1.winstonLog.logError(`Error in countWhere ${model.modelName}: ${error}`);
421 return Q.reject(error);
422 });
423}
424exports.countWhere = countWhere;
425function distinctWhere(model, query) {
426 let queryObj = model.find(mongooseHelper.setShardCondition(model, query)).distinct();
427 //winstonLog.logInfo(`findWhere query is ${query}`);
428 return Q.nbind(queryObj.exec, queryObj)()
429 .then(result => {
430 // update embedded property, if any
431 return Q.resolve(result);
432 }).catch(error => {
433 winstonLog_1.winstonLog.logError(`Error in distinctWhere ${model.modelName}: ${error}`);
434 return Q.reject(error);
435 });
436}
437exports.distinctWhere = distinctWhere;
438/**
439 * Query collection and then populate child objects with relationship
440 * Usage - Search object with given condition
441 * @param model
442 * @param query
443 * @param select {Array<string> | any} In case it is an array of string, it selects the specified keys mentioned in the array. In case it is an Object, it sets the JS object as the projection key
444 * @param sort
445 * @param skip
446 * @param limit
447 */
448function findWhere(model, query, select, queryOptions, toLoadChilds, sort, skip, limit) {
449 //console.log("findWhere " + model.modelName);
450 let lt, gt, lte, gte, lt_value, lte_value, gt_value, gte_value;
451 var sel = {};
452 let order = undefined;
453 if (select instanceof Array) {
454 select.forEach(x => {
455 sel[x] = 1;
456 });
457 }
458 else if (select) {
459 sel = select;
460 }
461 if (queryOptions) {
462 if (queryOptions.limit != null)
463 limit = Number.parseInt(queryOptions.limit.toString());
464 if (queryOptions.skip != null)
465 skip = Number.parseInt(queryOptions.skip.toString());
466 if (queryOptions.lt != null) {
467 lt = queryOptions.lt;
468 }
469 if (queryOptions.gt != null) {
470 gt = queryOptions.gt;
471 }
472 if (queryOptions.lt_value != null) {
473 lt_value = Number.parseInt(queryOptions.lt_value);
474 }
475 if (queryOptions.gt_value != null) {
476 gt_value = Number.parseInt(queryOptions.gt_value);
477 }
478 if (queryOptions.lt != null) {
479 lte = queryOptions.lte;
480 }
481 if (queryOptions.gt != null) {
482 gte = queryOptions.gte;
483 }
484 if (queryOptions.lt_value != null) {
485 lte_value = Number.parseInt(queryOptions.lte_value);
486 }
487 if (queryOptions.gt_value != null) {
488 gte_value = Number.parseInt(queryOptions.gte_value);
489 }
490 if (queryOptions.sort != null) {
491 sort = queryOptions.sort;
492 if (queryOptions.order != null && queryOptions.order === 'desc') {
493 let descSort = {};
494 descSort[sort] = -1;
495 sort = descSort;
496 }
497 }
498 }
499 let newModels = {};
500 let obj = instance_service_1.InstanceService.getInstanceFromType(model_entity_1.getEntity(model.modelName), true);
501 if (obj.getShardKey) {
502 let key = obj.getShardKey();
503 if (query[key]) {
504 if (CoreUtils.isJSON(query[key])) {
505 if (query[key]['$in']) {
506 query[key]['$in'].forEach(x => {
507 let newModel = mongooseHelper.getChangedModelForDynamicSchema(model, x);
508 newModels[newModel.modelName] = newModel;
509 });
510 }
511 }
512 else {
513 // get shard collection
514 let newModel = mongooseHelper.getChangedModelForDynamicSchema(model, query[key]);
515 newModels[newModel.modelName] = newModel;
516 }
517 }
518 if (Object.keys(newModels).length == 0) {
519 // find all the collection name and execute the query
520 mongooseHelper.getAllTheShards(model).forEach(x => {
521 newModels[x.modelName] = x;
522 });
523 }
524 }
525 else {
526 newModels[model.modelName] = model;
527 }
528 let asyncCalls = [];
529 Object.keys(newModels).forEach(x => {
530 let queryObj = newModels[x].find(mongooseHelper.setShardCondition(model, query), sel).lean();
531 if (sort) {
532 queryObj = queryObj.sort(sort);
533 }
534 if (skip) {
535 queryObj = queryObj.skip(skip);
536 }
537 if (limit) {
538 queryObj = queryObj.limit(limit);
539 }
540 if (gt && gt_value != undefined) {
541 queryObj = queryObj.gt(gt, gt_value);
542 }
543 if (lt && lt_value != undefined) {
544 queryObj = queryObj.lt(lt, lt_value);
545 }
546 if (gte && gte_value != undefined) {
547 queryObj = queryObj.gte(gte, gte_value);
548 }
549 if (lte && lte_value != undefined) {
550 queryObj = queryObj.lte(lte, lte_value);
551 }
552 asyncCalls.push(Q.nbind(queryObj.exec, queryObj)());
553 });
554 return Q.allSettled(asyncCalls).then(res => {
555 let result = [];
556 result = res.map(x => x.value).reduce((prev, current) => {
557 return prev.concat(current);
558 });
559 //winstonLog.logInfo(`findWhere query is ${query}`);
560 // update embedded property, if any
561 if (toLoadChilds != undefined && toLoadChilds == false) {
562 mongooseHelper.transformAllEmbeddedChildern1(model, result);
563 //console.log("findWhere end" + model.modelName);
564 return result;
565 }
566 var asyncCalls = [];
567 asyncCalls.push(mongooseHelper.embeddedChildren1(model, result, false));
568 return Q.allSettled(asyncCalls).then(r => {
569 //console.log("findWhere end" + model.modelName);
570 return result;
571 });
572 }).catch(error => {
573 winstonLog_1.winstonLog.logError(`Error in findWhere ${model.modelName}: ${error}`);
574 return Q.reject(error);
575 });
576 // winstonLog.logInfo(`findWhere query is ${query}`);
577 // return Q.nbind(model.find, model)(query)
578 // .then(result => {
579 // return toObject(result);
580 // }).catch(error => {
581 // winstonLog.logError(`Error in findWhere ${error}`);
582 // return error;
583 // });
584}
585exports.findWhere = findWhere;
586/**
587 * Usage - find object with given object id
588 * @param model
589 * @param id
590 */
591function findOne(model, id, donotLoadChilds) {
592 //console.log("findOne " + model.modelName);
593 let newModel = mongooseHelper.getChangedModelForDynamicSchema(model, id);
594 return newModel.findOne(mongooseHelper.setShardCondition(model, { '_id': id })).lean().then(result => {
595 return mongooseHelper.embeddedChildren1(model, [result], false, donotLoadChilds)
596 .then(r => {
597 //console.log("findOne end" + model.modelName);
598 return result;
599 });
600 }).catch(error => {
601 winstonLog_1.winstonLog.logError(`Error in findOne ${model.modelName}: ${error}`);
602 return Q.reject(error);
603 });
604}
605exports.findOne = findOne;
606/**
607 * Usage - find the object with given {property : value}
608 * @param model
609 * @param fieldName
610 * @param value
611 */
612function findByField(model, fieldName, value) {
613 //console.log("findByField " + model.modelName);
614 var param = {};
615 param[fieldName] = value;
616 return model.findOne(mongooseHelper.setShardCondition(model, param)).lean().then(result => {
617 return mongooseHelper.embeddedChildren1(model, [result], false)
618 .then(r => {
619 //console.log("findByField end" + model.modelName);
620 return result;
621 });
622 }, err => {
623 winstonLog_1.winstonLog.logError(`Error in findByField ${model.modelName}: ${err}`);
624 return Q.reject(err);
625 });
626}
627exports.findByField = findByField;
628/**
629 * Usage - Find all the objects with given ids
630 * @param model
631 * @param ids
632 */
633function findMany(model, ids, toLoadEmbeddedChilds) {
634 if (!ids || !ids.length)
635 return Q.when([]);
636 //console.log("findMany " + model.modelName);
637 if (toLoadEmbeddedChilds == undefined) {
638 toLoadEmbeddedChilds = false;
639 }
640 let newModels = mongooseHelper.getAllShardModelsFromIds(model, ids);
641 let asyncCalls = [];
642 Object.keys(newModels).forEach(x => {
643 asyncCalls.push(newModels[x].find(mongooseHelper.setShardCondition(model, {
644 '_id': {
645 $in: ids.map(x => Utils.getCastObjectId(model, x))
646 }
647 })).lean());
648 });
649 return Q.allSettled(asyncCalls).then(res => {
650 let result = [];
651 result = res.map(x => x.value).reduce((prev, current) => {
652 return prev.concat(current);
653 });
654 if (result.length !== ids.length) {
655 let oneId = "";
656 if (ids && ids.length) {
657 oneId = ids[0];
658 }
659 var error = 'findmany - numbers of items found:' + result.length + 'number of items searched: ' + ids.length + ' for model: ' + model.modelName + ' one of the id searched is: ' + oneId;
660 winstonLog_1.winstonLog.logError(`Error in findMany ${error}`);
661 return Q.reject(error);
662 }
663 if (toLoadEmbeddedChilds) {
664 let asyncCalls = [];
665 asyncCalls.push(mongooseHelper.embeddedChildren1(model, result, false));
666 //console.log("findMany end" + model.modelName);
667 return Q.allSettled(asyncCalls).then(r => {
668 return result;
669 });
670 }
671 else {
672 mongooseHelper.transformAllEmbeddedChildern1(model, result);
673 //console.log("findMany end" + model.modelName);
674 return result;
675 }
676 }).catch(error => {
677 winstonLog_1.winstonLog.logError(`Error in findMany ${model.modelName}: ${error}`);
678 return Q.reject(error);
679 });
680}
681exports.findMany = findMany;
682/**
683 * find object with the given id.
684 * Check if property has a relationship. If yes, then find all the child objects and return child
685 * @param model
686 * @param id
687 * @param prop
688 */
689function findChild(model, id, prop) {
690 //console.log("findChild " + model.modelName);
691 let newModel = mongooseHelper.getChangedModelForDynamicSchema(model, id);
692 return newModel.findOne(mongooseHelper.setShardCondition(model, { '_id': id })).lean().then(res => {
693 var metas = CoreUtils.getAllRelationsForTargetInternal(model_entity_1.getEntity(model.modelName));
694 if (Enumerable.from(metas).any(x => x.propertyKey == prop)) {
695 // create new object and add only that property for which we want to do eagerloading
696 var result = {};
697 result[prop] = res;
698 return mongooseHelper.embeddedChildren1(model, [result], true)
699 .then(r => {
700 //console.log("findChild end" + model.modelName);
701 return result[prop];
702 });
703 }
704 //console.log("findChild end" + model.modelName);
705 return res;
706 }).catch(error => {
707 winstonLog_1.winstonLog.logError(`Error in findChild ${model.modelName}: ${error}`);
708 return Q.reject(error);
709 });
710}
711exports.findChild = findChild;
712/**
713 * case 1: all new - create main item and child separately and embed if true
714 * case 2: some new, some update - create main item and update/create child accordingly and embed if true
715 * @param obj
716 */
717function post(model, obj) {
718 //console.log("post " + model.modelName);
719 mongooseHelper.updateWriteCount();
720 let clonedObj = mongooseHelper.removeTransientProperties(model, obj);
721 clonedObj[constants_1.ConstantKeys.TempId] = clonedObj._id ? clonedObj._id : Utils.autogenerateIds(model);
722 return mongooseHelper.addChildModelToParent(model, [clonedObj])
723 .then(result => {
724 //try {
725 // mongooseHelper.autogenerateIdsForAutoFields(model, clonedObj);
726 // //Object.assign(obj, clonedObj);
727 //} catch (ex) {
728 // //console.log(ex);
729 // return Q.reject(ex);
730 //}
731 if (clonedObj[constants_1.ConstantKeys.TempId]) {
732 clonedObj._id = clonedObj[constants_1.ConstantKeys.TempId];
733 delete clonedObj[constants_1.ConstantKeys.TempId];
734 }
735 mongooseHelper.setUniqueIdFromShard(clonedObj);
736 mongooseHelper.setShardCondition(model, clonedObj);
737 // assign empty array for not defined properties
738 if (dynamic_schema_1._arrayPropListSchema[model.modelName]) {
739 dynamic_schema_1._arrayPropListSchema[model.modelName].forEach(prop => {
740 if (!clonedObj[prop]) {
741 clonedObj[prop] = [];
742 }
743 });
744 }
745 let newModel = mongooseHelper.getNewModelFromObject(model, clonedObj);
746 return Q.nbind(newModel.create, newModel)(clonedObj).then(result => {
747 let resObj = Utils.toObject(result);
748 Object.assign(obj, resObj);
749 return mongooseHelper.embeddedChildren1(model, [obj], false)
750 .then(r => {
751 //console.log("post end " + model.modelName);
752 return obj;
753 });
754 });
755 }).catch(error => {
756 winstonLog_1.winstonLog.logError(`Error in post ${model.modelName}: ${error}`);
757 return Q.reject(error);
758 });
759}
760exports.post = post;
761/**
762 * Delete object with given id. Check if, any children have deletecase=true, then delete children from master table
763 * Update parent document for all the deleted objects
764 * Usage - Delete object given id
765 * @param model
766 * @param id
767 */
768function del(model, id) {
769 //console.log("delete " + model.modelName);
770 let newModel = mongooseHelper.getChangedModelForDynamicSchema(model, id);
771 return newModel.findByIdAndRemove(mongooseHelper.setShardCondition(model, { '_id': id })).lean().then((response) => {
772 return mongooseHelper.deleteCascade(model, [response]).then(x => {
773 return mongooseHelper.deleteEmbeddedFromParent(model, entity_change_1.EntityChange.delete, [response])
774 .then(res => {
775 //console.log("delete end" + model.modelName);
776 return ({ delete: 'success' });
777 });
778 });
779 })
780 .catch(err => {
781 winstonLog_1.winstonLog.logError(`delete failed ${model.modelName}: ${err}`);
782 return Q.reject({ delete: 'failed', error: err });
783 });
784}
785exports.del = del;
786/**
787 * Sequetially delete the objects
788 * @param modelte
789 * @param ids
790 */
791function bulkDel(model, objs) {
792 //console.log("bulkDel " + model.modelName);
793 var asyncCalls = [];
794 var ids = [];
795 Enumerable.from(objs).forEach(x => {
796 if (CoreUtils.isJSON(x)) {
797 ids.push(x._id);
798 }
799 else {
800 ids.push(x);
801 }
802 });
803 if (!ids || !ids.length)
804 return Q.when([]);
805 let newModels = mongooseHelper.getAllShardModelsFromIds(model, ids);
806 Object.keys(newModels).forEach(x => {
807 asyncCalls.push(newModels[x].find(mongooseHelper.setShardCondition(model, {
808 '_id': {
809 $in: ids
810 }
811 })).lean());
812 });
813 return Q.allSettled(asyncCalls).then(res => {
814 let parents = [];
815 parents = res.map(x => x.value).reduce((prev, current) => {
816 return prev.concat(current);
817 });
818 asyncCalls = [];
819 Object.keys(newModels).forEach(x => {
820 asyncCalls.push(Q.nbind(newModels[x].remove, newModels[x])(mongooseHelper.setShardCondition(model, {
821 '_id': {
822 $in: ids
823 }
824 })));
825 });
826 return Q.allSettled(asyncCalls).then(result => {
827 return mongooseHelper.deleteCascade(model, parents).then(success => {
828 let asyncCalls = [];
829 return mongooseHelper.deleteEmbeddedFromParent(model, entity_change_1.EntityChange.delete, parents).then(x => {
830 //console.log("bulkDel end" + model.modelName);
831 return ({ delete: 'success' });
832 });
833 });
834 }).catch(err => {
835 winstonLog_1.winstonLog.logError(`bulkDel failed ${model.modelName}: ${err}`);
836 return Q.reject('bulkDel failed');
837 });
838 });
839}
840exports.bulkDel = bulkDel;
841/**
842 * Check if any child object need to be added, if yes, then add those child objects.
843 * update the object with propertie. And then update the parent objects.
844 * Usage - Update the object with given object id
845 * @param model
846 * @param id
847 * @param obj
848 */
849function put(model, id, obj) {
850 //console.log("put " + model.modelName);
851 // Mayank - Check with suresh how to reject the changes in optimistic locking
852 return bulkPut(model, [obj]).then((res) => {
853 if (res.length) {
854 //this merging is wrong, as we cannnot send transient props in API rsult.Inconsistency @Ratnesh sugestion
855 Object.assign(obj, res[0]);
856 //console.log("put end" + model.modelName);
857 return obj;
858 }
859 //console.log("put end" + model.modelName);
860 return [];
861 }).catch(error => {
862 winstonLog_1.winstonLog.logError(`Error in put ${model.modelName}: ${error}`);
863 return Q.reject(error);
864 });
865}
866exports.put = put;
867/**
868 * Check if any child object need to be added, if yes, then add those child objects.
869 * update the object with propertie. And then update the parent objects.
870 * Usage - Update the object with given object id
871 * @param model
872 * @param id
873 * @param obj
874 */
875function patch(model, id, obj) {
876 //console.log("patch " + model.modelName);
877 // need to set id in case id is not supplied in patched obj
878 obj._id = id;
879 // Mayank - Check with suresh how to reject the changes in optimistic locking
880 return bulkPatch(model, [obj]).then((res) => {
881 if (res.length)
882 return res[0];
883 return [];
884 }).catch(error => {
885 winstonLog_1.winstonLog.logError(`Error in patch ${model.modelName}: ${error}`);
886 return Q.reject(error);
887 });
888}
889exports.patch = patch;
890/**
891 * Check whether decorator is applied or not.
892 * @param path
893 * @param decorator
894 * @param propertyKey
895 */
896function isDecoratorApplied(model, decorator, propertyKey) {
897 var isDecoratorPresent = false;
898 let repo = model_entity_1.repoFromModel[model.modelName];
899 var repoEntity = repo && repo.getEntityType();
900 var optimisticLock = repoEntity && utils_1.MetaUtils.getMetaData(repoEntity, decorator, propertyKey);
901 if (optimisticLock) {
902 isDecoratorPresent = true;
903 }
904 return isDecoratorPresent;
905}
906
907//# sourceMappingURL=mongoose-model.js.map