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/hw7/Claudio_Maggioni/routes/utils.js

71 lines
1.5 KiB
JavaScript
Raw Normal View History

2019-11-11 15:58:06 +00:00
// 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 = err instanceof mongoose.CastError ||
err instanceof mongoose.TypeError ? 400 : 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')) {
2019-11-13 10:04:39 +00:00
if (req.query.ajax === 'true' && list) {
res.render('server_side.dust', { favs });
} else if (list) {
res.render('favourites.dust', { favs });
} else {
res.render('favorite.dust', favs);
}
2019-11-11 15:58:06 +00:00
} 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 };