111 lines
2.2 KiB
JavaScript
111 lines
2.2 KiB
JavaScript
const errors = require('restify-errors');
|
|
|
|
const Item = require('../models/item');
|
|
|
|
module.exports = function(server) {
|
|
server.post('/items', (req, res, next) => {
|
|
if (!req.is('application/json')) {
|
|
return next(
|
|
new errors.InvalidContentError("Expects 'application/json'"),
|
|
);
|
|
}
|
|
|
|
let data = req.body || {};
|
|
|
|
let item = new Item(data);
|
|
item.save(function(err) {
|
|
if (err) {
|
|
console.error(err);
|
|
return next(new errors.InternalError(err.message));
|
|
next();
|
|
}
|
|
|
|
res.send(201);
|
|
next();
|
|
});
|
|
});
|
|
|
|
server.get('/items', (req, res, next) => {
|
|
Item.apiQuery(req.params, function(err, docs) {
|
|
if (err) {
|
|
console.error(err);
|
|
return next(
|
|
new errors.InvalidContentError(err.errors.name.message),
|
|
);
|
|
}
|
|
|
|
res.send(docs);
|
|
next();
|
|
});
|
|
});
|
|
|
|
server.get('/items/:item_id', (req, res, next) => {
|
|
Item.findOne({ _id: req.params.item_id }, function(err, doc) {
|
|
if (err) {
|
|
console.error(err);
|
|
return next(
|
|
new errors.InvalidContentError(err.errors.name.message),
|
|
);
|
|
}
|
|
|
|
res.send(doc);
|
|
next();
|
|
});
|
|
});
|
|
|
|
server.put('/items/:item_id', (req, res, next) => {
|
|
if (!req.is('application/json')) {
|
|
return next(
|
|
new errors.InvalidContentError("Expects 'application/json'"),
|
|
);
|
|
}
|
|
|
|
let data = req.body || {};
|
|
|
|
if (!data._id) {
|
|
data = Object.assign({}, data, { _id: req.params.item_id });
|
|
}
|
|
|
|
Item.findOne({ _id: req.params.item_id }, function(err, doc) {
|
|
if (err) {
|
|
console.error(err);
|
|
return next(
|
|
new errors.InvalidContentError(err.errors.name.message),
|
|
);
|
|
} else if (!doc) {
|
|
return next(
|
|
new errors.ResourceNotFoundError(
|
|
'The resource you requested could not be found.',
|
|
),
|
|
);
|
|
}
|
|
|
|
Item.update({ _id: data._id }, data, function(err) {
|
|
if (err) {
|
|
console.error(err);
|
|
return next(
|
|
new errors.InvalidContentError(err.errors.name.message),
|
|
);
|
|
}
|
|
|
|
res.send(200, data);
|
|
next();
|
|
});
|
|
});
|
|
});
|
|
|
|
server.del('/items/:item_id', (req, res, next) => {
|
|
Item.deleteOne({ _id: req.params.item_id }, function(err) {
|
|
if (err) {
|
|
console.error(err);
|
|
return next(
|
|
new errors.InvalidContentError(err.errors.name.message),
|
|
);
|
|
}
|
|
|
|
res.send(204);
|
|
next();
|
|
});
|
|
});
|
|
};
|