-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
65 lines (53 loc) · 1.51 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
'use strict';
const _ = require('lodash');
module.exports = function(sails) {
/**
* Checks for the existence of the record in the first parameter.
* If it can't be found, the record in the second parameter is created,
* otherwise it is updated with the second parameter.
*
* @param {Object} criteria The criteria used to find the record.
* If not found and no 'values' is provided,
* it is also the record that will be created.
* @param {Object} values The object that you would like to update or
* create.
* @return {Promise}
*/
function updateOrCreate(criteria, values) {
return new Promise((resolve, reject) => {
if (!values) {
values = criteria.where ? criteria.where : criteria;
}
this.findOne(criteria)
.then((result) => {
if (result) {
return this.update(criteria, values);
}
return this.create(values);
})
.then((data) => {
if (Array.isArray(data)) {
data = _.first(data);
}
return data;
})
.then(resolve)
.catch(reject);
});
}
return {
/**
* Default configuration
*/
defaults: {
__configKey__: {
name: 'update-or-create'
}
},
configure: function() {
// This config will make `updateOrCreate` method
// available in all models.
sails.config.models.updateOrCreate = updateOrCreate;
}
};
};