2017-11-15 16:59:12 +01:00
|
|
|
const _ = require('lodash');
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
find: async function (params) {
|
2017-11-29 15:42:11 +01:00
|
|
|
return this.query(function(qb) {
|
2017-11-28 15:32:25 +01:00
|
|
|
_.forEach(params.where, (where, key) => {
|
2017-11-29 15:42:11 +01:00
|
|
|
qb.where(key, where[0].symbol, where[0].value);
|
2017-11-15 16:59:12 +01:00
|
|
|
});
|
2017-11-28 15:32:25 +01:00
|
|
|
|
|
|
|
if (params.sort) {
|
|
|
|
qb.orderBy(params.sort);
|
|
|
|
}
|
|
|
|
|
|
|
|
qb.offset(params.start);
|
|
|
|
|
|
|
|
qb.limit(params.limit);
|
|
|
|
}).fetchAll({
|
|
|
|
withRelated: _.keys(_.groupBy(_.reject(this.associations, {autoPopulate: false}), 'alias'))
|
|
|
|
});
|
2017-11-15 16:59:12 +01:00
|
|
|
},
|
|
|
|
|
|
|
|
count: async function (params) {
|
|
|
|
return await this
|
|
|
|
.forge()
|
|
|
|
.count();
|
|
|
|
},
|
|
|
|
|
|
|
|
findOne: async function (params) {
|
2017-11-28 15:32:25 +01:00
|
|
|
if (_.get(params, 'where._id')) {
|
|
|
|
params.where.id = params.where._id;
|
|
|
|
delete params.where._id;
|
|
|
|
}
|
|
|
|
|
2017-11-15 16:59:12 +01:00
|
|
|
const record = await this
|
2017-11-28 15:32:25 +01:00
|
|
|
.forge(params.where)
|
2017-11-15 16:59:12 +01:00
|
|
|
.fetch({
|
|
|
|
withRelated: this.associations.map(x => x.alias)
|
|
|
|
});
|
|
|
|
|
|
|
|
return record ? record.toJSON() : record;
|
|
|
|
},
|
|
|
|
|
|
|
|
create: async function (params) {
|
2017-11-29 17:09:19 +01:00
|
|
|
return this
|
2017-11-15 16:59:12 +01:00
|
|
|
.forge()
|
2017-11-29 17:09:19 +01:00
|
|
|
.save(Object.keys(params).reduce((acc, current) => {
|
2017-11-20 16:28:50 +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
|
|
|
}
|
|
|
|
|
|
|
|
return acc;
|
|
|
|
}, {}));
|
|
|
|
},
|
|
|
|
|
|
|
|
update: async function (params) {
|
2017-11-29 18:45:51 +01:00
|
|
|
if (_.get(params, '_id')) {
|
|
|
|
params.id = params._id;
|
|
|
|
delete params._id;
|
2017-11-15 16:59:12 +01:00
|
|
|
}
|
|
|
|
|
2017-11-29 18:45:51 +01:00
|
|
|
return this.forge({
|
|
|
|
[this.primaryKey]: params[this.primaryKey]
|
|
|
|
})
|
|
|
|
.save(params, {
|
|
|
|
patch: true
|
|
|
|
});
|
2017-11-15 16:59:12 +01:00
|
|
|
},
|
|
|
|
|
|
|
|
delete: async function (params) {
|
|
|
|
return await this
|
|
|
|
.forge({
|
2017-11-29 18:45:51 +01:00
|
|
|
[this.primaryKey]: params._id
|
2017-11-15 16:59:12 +01:00
|
|
|
})
|
|
|
|
.destroy();
|
|
|
|
},
|
|
|
|
|
2017-11-29 16:24:11 +01:00
|
|
|
search: async function (params) {
|
|
|
|
return this
|
|
|
|
.query(function(qb) {
|
|
|
|
qb
|
|
|
|
.where('username', 'LIKE', `%${params.id}%`)
|
|
|
|
.orWhere('email', 'LIKE', `%${params.id}%`);
|
|
|
|
})
|
|
|
|
.fetchAll();
|
2017-11-15 16:59:12 +01:00
|
|
|
}
|
|
|
|
};
|