UNPKG

11.9 kBJavaScriptView Raw
1"use strict";
2const Q = require('q');
3const utils_1 = require("../core/metadata/utils");
4const MongooseModel = require('./mongoose-model');
5const model_entity_1 = require('../core/dynamic/model-entity');
6const winstonLog_1 = require('../logging/winstonLog');
7const Utils = require('./utils');
8const utils = require('../mongoose/utils');
9const principalContext_1 = require('../security/auth/principalContext');
10const configUtil = require('../core/utils');
11const db_1 = require('./db');
12const constants_1 = require('../core/constants');
13var hash = require('object-hash');
14class MongooseService {
15 constructor() {
16 }
17 updateWriteCount() {
18 if (principalContext_1.PrincipalContext) {
19 var count = principalContext_1.PrincipalContext.get('cacheCount');
20 if (!count) {
21 count = 0;
22 }
23 principalContext_1.PrincipalContext.save('cacheCount', ++count);
24 }
25 }
26 startTransaction(param) {
27 return Q.when(true);
28 }
29 commitTransaction(param) {
30 return Q.when(true);
31 }
32 rollbackTransaction(param) {
33 return Q.when(true);
34 }
35 bulkPost(repoPath, objArr, batchSize) {
36 return MongooseModel.bulkPost(this.getModel(repoPath), objArr, batchSize);
37 }
38 bulkDel(repoPath, objArr) {
39 return MongooseModel.bulkDel(this.getModel(repoPath), objArr).then(result => {
40 objArr.forEach(x => this.deletEntityFromCache(repoPath, CacheConstants.idCache, x._id));
41 return result;
42 });
43 }
44 bulkPut(repoPath, objArr, batchSize, donotLoadChilds) {
45 return MongooseModel.bulkPut(this.getModel(repoPath), objArr, batchSize, donotLoadChilds).then(results => {
46 results.forEach((x) => {
47 if (donotLoadChilds) {
48 x.__partialLoaded = true;
49 }
50 this.setEntityIntoCache(repoPath, CacheConstants.idCache, x._id, x);
51 });
52 return results;
53 });
54 }
55 bulkPatch(repoPath, objArr) {
56 return MongooseModel.bulkPatch(this.getModel(repoPath), objArr).then(results => {
57 results.forEach(x => this.setEntityIntoCache(repoPath, CacheConstants.idCache, x._id, x));
58 return results;
59 });
60 }
61 bulkPutMany(repoPath, objIds, obj) {
62 return MongooseModel.bulkPutMany(this.getModel(repoPath), objIds, obj).then(results => {
63 //results && results.forEach((x: BaseModel) => {
64 // // in bulkPutMany we do not load egarLoading properties (children objects) so its partially loaded
65 // x.__partialLoaded = true;
66 // this.setEntityIntoCache(repoPath, CacheConstants.idCache, x._id, x);
67 //});
68 return results;
69 });
70 }
71 findAll(repoPath) {
72 return MongooseModel.findAll(this.getModel(repoPath));
73 }
74 findWhere(repoPath, query, selectedFields, queryOptions, toLoadChilds) {
75 let hashEntity = hash(JSON.stringify(query));
76 let cacheValueIds = this.getEntityFromCache(repoPath, CacheConstants.hashCache, hashEntity);
77 if (cacheValueIds) {
78 // get objects from cache only if previous findwhere does not cached with selectedFields
79 let cachedValueResults = cacheValueIds.map(id => this.getEntityFromCache(repoPath, CacheConstants.idCache, id))
80 .filter((x) => x && !x.__selectedFindWhere && !x.__partialLoaded);
81 if (cacheValueIds.length === cachedValueResults.length) {
82 console.log("cache hit success findWhere " + repoPath + " count " + cachedValueResults.length);
83 this.updateWriteCount();
84 return Q.when(cachedValueResults);
85 }
86 }
87 return MongooseModel.findWhere(this.getModel(repoPath), query, selectedFields, queryOptions, toLoadChilds).then((results) => {
88 results.forEach(result => {
89 if (selectedFields && selectedFields.length > 0) {
90 result.__selectedFindWhere = true;
91 }
92 // if selected fields is empty or undefined and toLoadChilds is false, then set partialLoaded true
93 if ((!selectedFields || selectedFields.length === 0) && toLoadChilds === false) {
94 result.__partialLoaded = true;
95 }
96 this.setEntityIntoCache(repoPath, CacheConstants.idCache, result._id, result);
97 });
98 this.setEntityIntoCache(repoPath, CacheConstants.hashCache, hashEntity, results.map(x => x._id));
99 return results;
100 });
101 }
102 countWhere(repoPath, query) {
103 return MongooseModel.countWhere(this.getModel(repoPath), query);
104 }
105 distinctWhere(repoPath, query) {
106 return MongooseModel.countWhere(this.getModel(repoPath), query);
107 }
108 findOne(repoPath, id, donotLoadChilds) {
109 let cacheValue = this.getEntityFromCache(repoPath, CacheConstants.idCache, id);
110 if (cacheValue && !cacheValue.__partialLoaded && !cacheValue.__selectedFindWhere) {
111 console.log("cache hit success findone " + repoPath);
112 this.updateWriteCount();
113 return Q.when(cacheValue);
114 }
115 return MongooseModel.findOne(this.getModel(repoPath), id, donotLoadChilds).then((result) => {
116 if (donotLoadChilds) {
117 result.__partialLoaded = true;
118 }
119 this.setEntityIntoCache(repoPath, CacheConstants.idCache, id, result);
120 return result;
121 });
122 }
123 findByField(repoPath, fieldName, value) {
124 return MongooseModel.findByField(this.getModel(repoPath), fieldName, value);
125 }
126 findMany(repoPath, ids, toLoadEmbeddedChilds) {
127 // do not cache embedded objects
128 if (!utils.isBasonOrStringType(ids[0])) {
129 return Q.when(ids);
130 }
131 let chachedValues = [];
132 let unChachedIds = [];
133 ids.forEach(id => {
134 let cacheValue = this.getEntityFromCache(repoPath, CacheConstants.idCache, id);
135 if (cacheValue) {
136 if (cacheValue.__selectedFindWhere) {
137 unChachedIds.push(id);
138 return;
139 }
140 if (toLoadEmbeddedChilds && cacheValue.__partialLoaded) {
141 unChachedIds.push(id);
142 return;
143 }
144 return chachedValues.push(cacheValue);
145 }
146 unChachedIds.push(id);
147 });
148 if (unChachedIds.length === 0) {
149 return Q.when(chachedValues);
150 }
151 if (chachedValues && chachedValues.length) {
152 console.log("cache hit success findMany " + repoPath + " count " + chachedValues.length);
153 this.updateWriteCount();
154 }
155 return MongooseModel.findMany(this.getModel(repoPath), unChachedIds, toLoadEmbeddedChilds).then((results) => {
156 results.forEach(result => {
157 if (!toLoadEmbeddedChilds) {
158 result.__partialLoaded = true;
159 }
160 this.setEntityIntoCache(repoPath, CacheConstants.idCache, result._id, result);
161 });
162 return chachedValues.concat(results);
163 });
164 }
165 findChild(repoPath, id, prop) {
166 return MongooseModel.findChild(this.getModel(repoPath), id, prop);
167 }
168 /**
169 * case 1: all new - create main item and child separately and embed if true
170 * case 2: some new, some update - create main item and update/create child accordingly and embed if true
171 * @param obj
172 */
173 post(repoPath, obj) {
174 return MongooseModel.post(this.getModel(repoPath), obj);
175 }
176 put(repoPath, id, obj) {
177 return MongooseModel.put(this.getModel(repoPath), id, obj).then(result => {
178 this.setEntityIntoCache(repoPath, CacheConstants.idCache, id, result);
179 return result;
180 });
181 }
182 del(repoPath, id) {
183 return MongooseModel.del(this.getModel(repoPath), id).then(result => {
184 this.deletEntityFromCache(repoPath, CacheConstants.idCache, id);
185 return result;
186 });
187 }
188 patch(repoPath, id, obj) {
189 return MongooseModel.patch(this.getModel(repoPath), id, obj).then(result => {
190 this.setEntityIntoCache(repoPath, CacheConstants.idCache, id, result);
191 return result;
192 });
193 }
194 getModel(repoPath, dynamicName) {
195 try {
196 let model = Utils.getCurrentDBModel(model_entity_1.pathRepoMap[repoPath].schemaName);
197 if (model && dynamicName) {
198 var meta = utils_1.MetaUtils.getMetaData(model_entity_1.getEntity(model.modelName), constants_1.Decorators.DOCUMENT);
199 if (meta && meta[0] && meta[0].params.dynamicName) {
200 model = db_1.getDbSpecifcModel(dynamicName, model.schema);
201 }
202 }
203 return model;
204 }
205 catch (e) {
206 winstonLog_1.winstonLog.logError(`Error in getMongooseModel ${e}`);
207 throw e;
208 }
209 }
210 getSortCondition(val) {
211 return val;
212 }
213 getLikeCondition(val) {
214 return {
215 $regex: '.*' + val + '.*'
216 };
217 }
218 getStartsWithCondition(val) {
219 return {
220 $regex: '^' + val + '.*'
221 };
222 }
223 getEntityFromCache(repoPath, param, id) {
224 // entityCache->modelName_path->hashEntity->{key: valueObj}
225 // ->idEntity->{key: valueObj}
226 if (!configUtil.config().Config.isCacheEnabled) {
227 return undefined;
228 }
229 let currentUser = principalContext_1.PrincipalContext.User;
230 if (currentUser && currentUser.entityCache && currentUser.entityCache[repoPath] &&
231 currentUser.entityCache[repoPath][param] && currentUser.entityCache[repoPath][param][id]) {
232 // if current context view is changed then clear cache objects
233 if (currentUser.cacheContext != currentUser.viewContext) {
234 currentUser.cacheContext = currentUser.viewContext;
235 currentUser.entityCache = [];
236 return undefined;
237 }
238 return currentUser.entityCache[repoPath][param][id];
239 }
240 return undefined;
241 }
242 setEntityIntoCache(repoPath, entityType, id, value) {
243 // entityCache->modelName_path->hashEntity->{key: valueObj}
244 // ->idEntity->{key: valueObj}
245 if (!configUtil.config().Config.isCacheEnabled) {
246 return undefined;
247 }
248 let currentUser = principalContext_1.PrincipalContext.User;
249 if (!currentUser) {
250 currentUser = {};
251 principalContext_1.PrincipalContext.User = currentUser;
252 }
253 if (!currentUser.entityCache) {
254 currentUser.entityCache = {};
255 }
256 if (!currentUser.entityCache[repoPath]) {
257 currentUser.entityCache[repoPath] = {};
258 }
259 if (!currentUser.entityCache[repoPath][entityType]) {
260 currentUser.entityCache[repoPath][entityType] = {};
261 }
262 currentUser.entityCache[repoPath][entityType][id] = value;
263 }
264 deletEntityFromCache(repoPath, param, id) {
265 if (!configUtil.config().Config.isCacheEnabled) {
266 return undefined;
267 }
268 let currentUser = principalContext_1.PrincipalContext.User;
269 if (currentUser && currentUser.entityCache && currentUser.entityCache[repoPath] &&
270 currentUser.entityCache[repoPath][param][id]) {
271 delete currentUser.entityCache[repoPath][param][id];
272 }
273 }
274 getPrimaryKey(repoPath) {
275 return '_id';
276 }
277}
278exports.MongooseService = MongooseService;
279class CacheConstants {
280}
281CacheConstants.idCache = "idCache";
282CacheConstants.hashCache = "hashCache";
283exports.CacheConstants = CacheConstants;
284
285//# sourceMappingURL=mongoose-service.js.map