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 };
|
|
|
|
|
|
|
|
|