Merge branch 'fix/relation-tests' of https://github.com/fabien/loopback-datasource-juggler into fix/relation-tests

This commit is contained in:
Fabien Franzen 2014-08-15 18:43:20 +02:00
commit 6b0bbed780
1 changed files with 44 additions and 0 deletions

View File

@ -1696,6 +1696,50 @@ EmbedsMany.prototype.embeddedList = function(modelInstance) {
return embeddedList; return embeddedList;
}; };
EmbedsMany.prototype.prepareEmbeddedInstance = function(inst) {
if (inst && inst.triggerParent !== 'function') {
var self = this;
var relationName = this.definition.name;
var modelInstance = this.modelInstance;
inst.triggerParent = function(actionName, callback) {
if (actionName === 'save' || actionName === 'destroy') {
var embeddedList = self.embeddedList();
if (actionName === 'destroy') {
var index = embeddedList.indexOf(inst);
if (index > -1) embeddedList.splice(index, 1);
}
modelInstance.updateAttribute(relationName,
embeddedList, function(err, modelInst) {
callback(err, err ? null : modelInst);
});
} else {
process.nextTick(callback);
}
};
var originalTrigger = inst.trigger;
inst.trigger = function(actionName, work, data, callback) {
if (typeof work === 'function') {
var originalWork = work;
work = function(next) {
originalWork.call(this, function(done) {
inst.triggerParent(actionName, function(err, inst) {
next(done); // TODO [fabien] - error handling?
});
});
};
}
originalTrigger.call(this, actionName, work, data, callback);
};
}
};
EmbedsMany.prototype.embeddedList = function(modelInstance) {
modelInstance = modelInstance || this.modelInstance;
var embeddedList = modelInstance[this.definition.name] || [];
embeddedList.forEach(this.prepareEmbeddedInstance.bind(this));
return embeddedList;
};
EmbedsMany.prototype.related = function(receiver, scopeParams, condOrRefresh, cb) { EmbedsMany.prototype.related = function(receiver, scopeParams, condOrRefresh, cb) {
var modelTo = this.definition.modelTo; var modelTo = this.definition.modelTo;
var modelInstance = this.modelInstance; var modelInstance = this.modelInstance;