101 lines
2.5 KiB
JavaScript
Raw Normal View History

const _ = require('lodash');
module.exports = {
find: async function (params, populate, raw = false) {
const query = this
2018-04-02 19:24:36 +02:00
.find(params.where)
.limit(Number(params.limit))
.sort(params.sort)
.skip(Number(params.skip))
.populate(populate || this.associations.map(x => x.alias).join(' '));
return raw ? query.lean() : query;
},
2018-05-22 17:11:35 +02:00
count: async function (params) {
return Number(await this
2018-05-22 17:11:35 +02:00
.where(params.where)
.count());
},
2018-06-07 14:35:09 +02:00
search: async function (params, populate) {
return [];
},
countSearch: async function (params = {}) {
return 0;
},
findOne: async function (params, populate, raw = true) {
const query = this
.findOne({
[this.primaryKey]: params[this.primaryKey] || params.id
})
.populate(populate || this.associations.map(x => x.alias).join(' '));
return raw ? query.lean() : query;
},
create: async function (params) {
// Exclude relationships.
const values = Object.keys(params.values).reduce((acc, current) => {
2018-02-27 16:53:06 +01:00
if (this._attributes[current] && this._attributes[current].type) {
acc[current] = params.values[current];
}
return acc;
}, {});
2017-12-06 15:58:20 +01:00
2018-04-25 12:23:53 +02:00
const request = await this.create(values)
.catch((err) => {
const message = err.message.split('index:');
const field = _.words(_.last(message).split('_')[0]);
const error = { message: `This ${field} is already taken`, field };
throw error;
});
// Transform to JSON object.
2018-04-25 12:23:53 +02:00
const entry = request.toJSON ? request.toJSON() : request;
// Extract relations.
2018-05-02 15:39:12 +02:00
const relations = this.associations.reduce((acc, association) => {
if (params.values[association.alias]) {
acc[association.alias] = params.values[association.alias];
}
return acc;
}, {});
return module.exports.update.call(this, {
[this.primaryKey]: entry[this.primaryKey],
2018-04-25 12:23:53 +02:00
values: _.assign({
2017-09-18 18:20:33 +02:00
id: entry[this.primaryKey]
2018-05-02 15:39:12 +02:00
}, relations)
});
},
update: async function (params) {
// Call the business logic located in the hook.
// This function updates no-relational and relational data.
return this.updateRelations(params);
},
delete: async function (params) {
2017-09-20 13:19:36 +02:00
// Delete entry.
return this
.remove({
2017-09-20 18:14:18 +02:00
[this.primaryKey]: params.id
});
},
deleteMany: async function (params) {
return this
.remove({
[this.primaryKey]: {
$in: params[this.primaryKey] || params.id
}
});
}
};