-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
83 lines (74 loc) · 2.08 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
var noop = function(){};
var SaveInvalid = module.exports = function(Model) {
Model.prototype.save = function(skipValidations, cb) {
var args = [].slice.call(arguments),
self = this,
operation = 'save',
isNew = this.isNew(),
fn, skipValidations;
skipValidations = args.shift();
if(typeof skipValidations == 'boolean') {
fn = args.pop() || noop;
} else {
fn = skipValidations || noop;
skipValidations = false;
}
if (!isNew) {
var changed = this.changed();
operation = 'update';
if(!changed) return fn(null, this);
}
var save = this.model[operation];
if (!this.isValid()) {
if(skipValidations) {
if(SaveInvalid.invalidAttr)
this.attrs[SaveInvalid.invalidAttr] = true;
if(SaveInvalid.completeAttr)
this.attrs[SaveInvalid.completeAttr] = false;
} else {
this.primary(null);
return fn(new Error('validation failed'));
}
} else {
if(SaveInvalid.invalidAttr)
this.attrs[SaveInvalid.invalidAttr] = false;
if(SaveInvalid.completeAttr)
this.attrs[SaveInvalid.completeAttr] = true;
}
this.run('saving', function(err) {
if(err) {
if(!skipValidations || err.message != 'validation failed') fn(err);
}
if(isNew) {
self.run('creating', function(err) {
if(err) {
if(!skipValidations || err.message != 'validation failed') fn(err);
}
save.apply(self, args.concat(res));
});
} else {
save.apply(self, args.concat(res));
}
});
function res(err, body) {
if (err) {
self.emit('error', err);
return fn(err);
}
if (body) {
self.primary(body.id || body._id);
for(var attr in self.model.attrs) {
self.attrs[attr] = body[attr];
}
}
self.dirty = {};
if(isNew) {
self.model.emit('create', self);
self.emit('create');
}
self.model.emit('save', self);
self.emit('save');
fn(null, self);
}
};
};