forked from offlinehacker/bookshelf-check-duplicates
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
60 lines (47 loc) · 1.34 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
'use strict';
var Promise = require('bluebird');
var _ = require('lodash');
function DuplicateError(field) {
this.name = 'DuplicateError';
this.message = 'DuplicateError: ' + field;
this.field = field;
}
DuplicateError.prototype = Error.prototype;
module.exports = function (bookshelf) {
var Model = bookshelf.Model;
bookshelf.Model = Model.extend({
constructor: function() {
Model.apply(this, arguments);
this.schema = this.schema || {};
if (this.duplicates) {
this.on('saving', this.validateDuplicates, this);
}
},
/**
* Validates for duplicates
* @throws {DuplicateError}
*/
validateDuplicates: function() {
var self = this;
return Promise.all(_.map(self.duplicates, function(field) {
var q = bookshelf.knex(self.tableName);
if (self._transaction) {
q = q.transacting(self._transaction);
}
q = q.where(field, self.get(field));
if (!_.isUndefined(self.id)) {
q = q.andWhereNot('id', self.id);
}
return q
.count('* AS count')
.limit(1)
.then(function(result) {
if (result && result[0].count > 0) {
throw new DuplicateError(field);
}
});
}));
}
});
bookshelf.Model.DuplicateError = DuplicateError;
};