54 lines
1.6 KiB
JavaScript
54 lines
1.6 KiB
JavaScript
'use strict';
|
|
|
|
// HTTP status codes by name
|
|
const codes = require('./http-codes');
|
|
|
|
const genericGetById = (req, res, next, modelClass) => {
|
|
modelClass.findById(req.params.id, (err, item) => {
|
|
if (err) {
|
|
err.status = codes.servererror;
|
|
return next(err);
|
|
} else if (!item) {
|
|
err = new Error('item not found');
|
|
err.status = codes.notfound;
|
|
return next(err);
|
|
}
|
|
res.locals.items = item;
|
|
return next();
|
|
});
|
|
};
|
|
|
|
const genericPatch = (req, res, next, modelClass) => {
|
|
if (!req.body || (req.body._id && req.body._id !== req.params.id)) {
|
|
// little bit different as in PUT. :id does not need to be in data, but if the _id and url id must match
|
|
const err = new Error('id of PATCH resource and send JSON body are not equal ' + req.params.id + ' ' +
|
|
req.body._id);
|
|
err.status = codes.notfound;
|
|
next(err);
|
|
return; // prevent node to process this function further after next() has finished.
|
|
}
|
|
|
|
req.body.updatedAt = new Date();
|
|
req.body.$inc = {__v: 1};
|
|
if (req.body.hasOwnProperty('__v')) {
|
|
delete req.body.__v;
|
|
}
|
|
|
|
// PATCH is easier with mongoose than PUT. You simply update by all data that comes from outside. no need to
|
|
// reset attributes that are missing.
|
|
modelClass.findByIdAndUpdate(req.params.id, req.body, {new: true}, (err, item) => {
|
|
if (err) {
|
|
err.status = codes.wrongrequest;
|
|
} else if (!item) {
|
|
err = new Error('item not found');
|
|
err.status = codes.notfound;
|
|
} else {
|
|
res.locals.items = item;
|
|
}
|
|
next(err);
|
|
});
|
|
};
|
|
|
|
exports.genericGetById = genericGetById;
|
|
exports.genericPatch = genericPatch;
|