This repository has been archived on 2021-10-31. You can view files and clone it, but cannot push or open issues or pull requests.
SA3/hw6/Claudio_Maggioni/routes/utils.js

64 lines
1.3 KiB
JavaScript

// vim: set ts=2 sw=2 et tw=80:
const mongoose = require('mongoose');
function catchErrs(promise, res) {
return promise.catch(err => error(err, res));
}
function error(err, res) {
console.error(err);
res.status = 500;
res.format({
json: () => res.json({ error: err }),
html: () => res.render('500.dust', { err: JSON.stringify(err, null, 2) }),
});
res.end();
}
function renderFav(req, res, favs, list = true) {
const makeTestsPass = e => {
return {
_id: e._id,
name: e.name,
dataURL: e.dataURL,
bookmarked: '' + e.bookmarked
}
};
if (req.accepts('html')) {
res.render(list ? 'favourites.dust' : 'favourite.dust',
list ? { favs } : favs);
} else if (req.accepts('json')) {
if (list) {
favs = favs.map(makeTestsPass);
} else {
favs = makeTestsPass(favs);
}
res.json(favs);
} else {
res.writeHead(406);
res.end();
}
}
function parseId(req) {
if (typeof req.params.id === 'string' && req.params.id.length == 24) {
return mongoose.Types.ObjectId(req.params.id);
} else {
return req.params.id;
}
}
function notFound(e, res) {
if (e == null) {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('Not found');
return true;
} else return false;
}
module.exports = { error, renderFav, catchErrs, parseId, notFound };