92 lines
2.0 KiB
JavaScript
Raw Normal View History

2017-11-15 16:59:12 +01:00
const _ = require('lodash');
module.exports = {
find: async function (params) {
return this
2017-11-15 17:27:07 +01:00
.find(params.where)
2017-11-15 16:59:12 +01:00
.limit(Number(params.limit))
.sort(params.sort)
2017-11-28 10:51:03 +01:00
.skip(Number(params.skip))
.populate(this.associations.map(x => x.alias).join(' '));
2017-11-15 16:59:12 +01:00
},
count: async function (params) {
return Number(await this
.count());
},
findOne: async function (params) {
if (!params[this.primaryKey] && params.id) {
params[this.primaryKey] = params.id;
delete params.id;
2017-12-14 16:12:39 +01:00
} else if (params.id) {
delete params.id;
}
2017-11-15 16:59:12 +01:00
return this
2017-11-16 14:29:49 +01:00
.findOne(params)
2017-11-15 16:59:12 +01:00
.populate(this.associations.map(x => x.alias).join(' '));
},
create: async function (params) {
2017-11-29 17:09:19 +01:00
return this.create(Object.keys(params).reduce((acc, current) => {
2017-11-16 14:12:03 +01:00
if (_.get(this._attributes, [current, 'type'])) {
2017-11-29 17:09:19 +01:00
acc[current] = params[current];
2017-11-15 16:59:12 +01:00
}
2017-12-06 11:47:39 +01:00
2017-11-15 16:59:12 +01:00
return acc;
2017-12-06 11:47:39 +01:00
}, {}))
.catch((error) => {
2017-12-06 15:11:55 +01:00
const field = _.last(_.words(error.message.split('_')[0]));
const err = { message: `This ${field} is already taken`, field };
throw err;
2017-12-06 11:47:39 +01:00
});
2017-11-15 16:59:12 +01:00
},
update: async function (params) {
2017-11-29 18:45:51 +01:00
return this.update({
[this.primaryKey]: params[this.primaryKey] || params.id
}, params, {
strict: false
2017-12-06 15:11:55 +01:00
})
.catch((error) => {
const field = _.last(_.words(error.message.split('_')[0]));
const err = { message: `This ${field} is already taken`, field };
throw err;
2017-11-29 18:45:51 +01:00
});
2017-11-15 16:59:12 +01:00
},
delete: async function (params) {
// Delete entry.
return this
.remove({
2017-11-29 18:45:51 +01:00
[this.primaryKey]: params[this.primaryKey] || params.id
2017-11-15 16:59:12 +01:00
});
},
search: async function (params) {
const re = new RegExp(params.id);
return this
.find({
'$or': [
{ username: re },
{ email: re }
]
});
2017-11-30 12:27:04 +01:00
},
countByRoles: async function () {
return this.aggregate([
{
$group: {
_id: "$role",
total: {$sum: 1}
}
}
]);
2017-11-15 16:59:12 +01:00
}
};