51 lines
1.0 KiB
JavaScript
Raw Normal View History

2015-10-01 00:30:16 +02:00
'use strict';
/**
* Module dependencies
*/
// Local utils.
const actionUtil = require('../actionUtil');
/**
* Find a specific entry
*/
2016-02-01 08:43:17 +01:00
module.exports = function findOne(_ctx) {
2015-10-01 00:30:16 +02:00
const deferred = Promise.defer();
// Return the model used.
const Model = actionUtil.parseModel(_ctx);
// Locate and validate the required `id` parameter.
const pk = actionUtil.requirePk(_ctx);
2016-02-02 16:31:11 +01:00
// Build criteria object
const criteria = {};
criteria[Model.primaryKey] = pk;
_.merge(criteria, actionUtil.parseSelect(_ctx));
2015-10-01 00:30:16 +02:00
// Init the query.
2016-02-02 16:31:11 +01:00
let query = Model.findOne(criteria);
2015-10-01 00:30:16 +02:00
query = actionUtil.populateEach(query, _ctx, Model);
query.exec(function found(err, matchingRecord) {
if (err) {
_ctx.status = 500;
deferred.reject(err);
}
if (!matchingRecord) {
_ctx.status = 404;
return deferred.reject({
message: 'No ' + Model.name + ' found with the specified `id`.'
});
}
// Record found.
deferred.resolve(matchingRecord);
});
return deferred.promise;
};