Skip to content

Commit

Permalink
Better handling of instance use after removal
Browse files Browse the repository at this point in the history
  • Loading branch information
notheotherben committed Mar 20, 2014
1 parent afb5bfc commit 1dbaff9
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
11 changes: 10 additions & 1 deletion lib/Instance.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ function Instance(model, doc, isNew) {

this.__state = {
model: model,
isNew: isNew,
isNew: isNew || false,
original: _.cloneDeep(doc),
modified: _.cloneDeep(doc)
};
Expand Down Expand Up @@ -159,6 +159,10 @@ Instance.prototype.save = function(conditions, changes, callback) {
var conditions = this.__state.model.uniqueConditions(this.__state.modified);
this.__state.model.collection.findOne(conditions, (function (err, latest) {
if (err) return onError(err);
if(!latest) {
this.__state.isNew = true;
return (callback || function () { })(null, this);
}

this.__state.model.onRetrieved(conditions, latest, callback || function () { }, (function (value) {
this.__state.model.fromSource(value);
Expand Down Expand Up @@ -204,8 +208,13 @@ Instance.prototype.refresh = Instance.prototype.update = function(callback) {
};

Instance.prototype.remove = Instance.prototype.delete = function(callback) {
/// <signature>
/// <summary>Removes this object from the database collection</summary>
/// </signature>
/// <signature>
/// <summary>Removes this object from the database collection</summary>
/// <param name="callback" value="callback(new Error())">A function to be called when the object has been removed</param>
/// </signature>

if(this.__state.isNew) return (callback || function() { })(null, 0);

Expand Down
28 changes: 26 additions & 2 deletions test/instance_db.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ describe('orm', function () {
billy2.age.should.eql(billy1.age);
done();
});
})
});
});
})
});
Expand All @@ -140,7 +140,7 @@ describe('orm', function () {
model.get('billy', function(err, billy) {
if(err) return done(err);
should.exist(billy);

billy.remove(function(err) {
if(err) return done(err);
billy.__state.isNew.should.be.true;
Expand All @@ -154,6 +154,30 @@ describe('orm', function () {
});
});
});

it('should set instance isNew to true after removal', function(done) {
model.create({
username: 'billy',
age: 10,
sessions: [{
id: 'aaaa',
expires: new Date()
}]
}, function(err, original) {
/// <param name="original" value="new model.Instance({})"/>
if(err) return done(err);

should.exist(original);
original.__state.isNew.should.be.false;

original.remove(function(err) {
should.not.exist(err);
original.__state.isNew.should.be.true;

done();
});
});
});
});
});
});
Expand Down

0 comments on commit 1dbaff9

Please sign in to comment.