MCPcopy Create free account
hub / github.com/dresende/node-orm2 / saveAssociations

Function saveAssociations

lib/Instance.js:276–344  ·  view source on GitHub ↗
(cb)

Source from the content-addressed store, hash-verified

274 }
275 };
276 var saveAssociations = function (cb) {
277 var pending = 1, errored = false, i, j;
278 var saveAssociation = function (accessor, instances) {
279 pending += 1;
280
281 instance[accessor](instances, function (err) {
282 if (err) {
283 if (errored) return;
284
285 errored = true;
286 return cb(err, true);
287 }
288
289 if (--pending === 0) {
290 return cb(null, true);
291 }
292 });
293 };
294
295 var _saveOneAssociation = function (assoc) {
296 if (!instance[assoc.name] || typeof instance[assoc.name] !== "object") return;
297 if (assoc.reversed) {
298 // reversed hasOne associations should behave like hasMany
299 if (!Array.isArray(instance[assoc.name])) {
300 instance[assoc.name] = [ instance[assoc.name] ];
301 }
302 for (var i = 0; i < instance[assoc.name].length; i++) {
303 if (!instance[assoc.name][i].isInstance) {
304 instance[assoc.name][i] = new assoc.model(instance[assoc.name][i]);
305 }
306 saveAssociation(assoc.setAccessor, instance[assoc.name][i]);
307 }
308 return;
309 }
310 if (!instance[assoc.name].isInstance) {
311 instance[assoc.name] = new assoc.model(instance[assoc.name]);
312 }
313
314 saveAssociation(assoc.setAccessor, instance[assoc.name]);
315 };
316
317 for (i = 0; i < opts.one_associations.length; i++) {
318 _saveOneAssociation(opts.one_associations[i]);
319 }
320
321
322 var _saveManyAssociation = function (assoc) {
323 var assocVal = instance[assoc.name];
324
325 if (!Array.isArray(assocVal)) return;
326 if (!opts.associations[assoc.name].changed) return;
327
328 for (j = 0; j < assocVal.length; j++) {
329 if (!assocVal[j].isInstance) {
330 assocVal[j] = new assoc.model(assocVal[j]);
331 }
332 }
333

Callers 2

saveNewFunction · 0.85
nextFunction · 0.85

Calls 3

_saveOneAssociationFunction · 0.85
_saveManyAssociationFunction · 0.85
cbFunction · 0.85

Tested by

no test coverage detected