Implemented persistent: true option for embedsOne

This commit is contained in:
Fabien Franzen 2014-09-07 13:10:23 +02:00
parent 95764232b9
commit 21e1083e88
2 changed files with 70 additions and 15 deletions

View File

@ -1775,18 +1775,28 @@ EmbedsOne.prototype.create = function (targetModelData, cb) {
var inst = this.build(targetModelData);
var err = inst.isValid() ? null : new ValidationError(inst);
if (err) {
return process.nextTick(function() {
cb(err);
});
}
var updateEmbedded = function() {
modelInstance.updateAttribute(propertyName,
inst, function(err) {
cb(err, err ? null : inst);
});
};
if (this.definition.options.persistent) {
inst.save(function(err) { // will validate
if (err) return cb(err, inst);
updateEmbedded();
});
} else {
var err = inst.isValid() ? null : new ValidationError(inst);
if (err) {
process.nextTick(function() {
cb(err);
});
} else {
updateEmbedded();
}
}
};
EmbedsOne.prototype.build = function (targetModelData) {
@ -2199,26 +2209,27 @@ EmbedsMany.prototype.create = function (targetModelData, cb) {
var inst = this.build(targetModelData);
var updateEmbeddedList = function() {
var updateEmbedded = function() {
modelInstance.updateAttribute(propertyName,
embeddedList, function(err, modelInst) {
cb(err, err ? null : inst);
});
}
};
if (this.definition.options.persistent) {
inst.save(function(err) { // will validate
if (err) return cb(err, inst);
updateEmbeddedList();
updateEmbedded();
});
} else {
var err = inst.isValid() ? null : new ValidationError(inst);
if (err) {
return process.nextTick(function() {
process.nextTick(function() {
cb(err);
});
} else {
updateEmbedded();
}
updateEmbeddedList();
}
};

View File

@ -1833,6 +1833,50 @@ describe('relations', function () {
});
describe('embedsOne - persisted model', function () {
// This test spefically uses the Memory connector
// in order to test the use of the auto-generated
// id, in the sequence of the related model.
before(function () {
db = getMemoryDataSource();
Person = db.define('Person', {name: String});
Passport = db.define('Passport',
{name:{type:'string', required: true}}
);
});
it('can be declared using embedsOne method', function (done) {
Person.embedsOne(Passport, {
options: {persistent: true}
});
db.automigrate(done);
});
it('should create an item - to offset id', function(done) {
Passport.create({name:'Wilma'}, function(err, p) {
should.not.exist(err);
p.id.should.equal(1);
p.name.should.equal('Wilma');
done();
});
});
it('should create an embedded item on scope', function(done) {
Person.create({name: 'Fred'}, function(err, p) {
should.not.exist(err);
p.passportItem.create({name: 'Fredric'}, function(err, passport) {
should.not.exist(err);
p.passport.id.should.eql(2);
p.passport.name.should.equal('Fredric');
done();
});
});
});
});
describe('embedsMany', function () {
var address1, address2;