98 lines
2.3 KiB
JavaScript
Raw Normal View History

const _ = require('lodash');
2019-04-09 18:35:49 +02:00
const { convertRestQueryParams, buildQuery } = require('strapi-utils');
2019-04-16 09:35:13 +02:00
module.exports = ({ model }) => ({
find(params, populate) {
2019-04-09 18:35:49 +02:00
const filters = convertRestQueryParams(params);
2019-04-16 09:35:13 +02:00
return model
.query(buildQuery({ model, filters }))
2019-04-09 18:35:49 +02:00
.fetchAll({
2019-04-16 09:35:13 +02:00
withRelated: populate || model.associations.map(x => x.alias),
2019-04-09 18:35:49 +02:00
})
.then(data => data.toJSON());
},
2019-04-16 09:35:13 +02:00
count(params = {}) {
2019-04-09 18:35:49 +02:00
const { where } = convertRestQueryParams(params);
2019-04-16 09:35:13 +02:00
return model.query(buildQuery({ model, filters: { where } })).count();
},
2019-04-16 09:35:13 +02:00
async findOne(params, populate) {
const primaryKey = params[model.primaryKey] || params.id;
if (primaryKey) {
params = {
2019-04-16 09:35:13 +02:00
[model.primaryKey]: primaryKey,
};
}
2019-04-16 09:35:13 +02:00
const record = await model.forge(params).fetch({
withRelated: populate || model.associations.map(x => x.alias),
});
return record ? record.toJSON() : record;
},
2019-04-16 09:35:13 +02:00
async create(params) {
return model
.forge()
.save(
Object.keys(params).reduce((acc, current) => {
if (
2019-04-16 09:35:13 +02:00
_.get(model._attributes, [current, 'type']) ||
_.get(model._attributes, [current, 'model'])
) {
acc[current] = params[current];
}
return acc;
2019-04-16 09:35:13 +02:00
}, {})
)
.catch(err => {
if (err.detail) {
const field = _.last(_.words(err.detail.split('=')[0]));
err = { message: `This ${field} is already taken`, field };
}
throw err;
});
},
2019-04-16 09:35:13 +02:00
async update(search, params = {}) {
if (_.isEmpty(params)) {
params = search;
}
2019-04-16 09:35:13 +02:00
const primaryKey = search[model.primaryKey] || search.id;
if (primaryKey) {
search = {
2019-04-16 09:35:13 +02:00
[model.primaryKey]: primaryKey,
};
} else {
2019-04-16 09:35:13 +02:00
const entry = await this.findOne(search);
search = {
2019-04-16 09:35:13 +02:00
[model.primaryKey]: entry[model.primaryKey] || entry.id,
};
}
2019-04-16 09:35:13 +02:00
return model
.forge(search)
.save(params, {
patch: true,
})
.catch(err => {
2019-05-14 09:30:10 +02:00
if (err && err.detail) {
const field = _.last(_.words(err.detail.split('=')[0]));
const error = { message: `This ${field} is already taken`, field };
throw error;
}
2019-05-14 09:30:10 +02:00
throw err;
});
2019-05-14 09:30:10 +02:00
},
2019-04-16 09:35:13 +02:00
});