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/hw5/Claudio_Maggioni/routes/favourites/router.js

134 lines
2.8 KiB
JavaScript

/** @module root/router */
'use strict';
// vim: set ts=2 sw=2 et tw=80:
const fs = require('fs');
const express = require('express');
const router = express.Router();
let id = 1;
function nextId() {
return id++;
}
function createFav(req, res) {
if (!req.body.name || !req.body.dataURL) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('Bad create form parameters');
return;
}
const favourite = {
_id: nextId(),
name: req.body.name,
dataURL: req.body.dataURL
};
req.app.locals.favourites.push(favourite);
req.app.locals.writeFavs();
res.status = 201;
renderOne(res, favourite);
}
router.post('/', createFav);
function renderAll(res, favs) {
res.format({
html: () => res.render('favourites.dust', { favs: favs }),
json: () => res.send(favs)
});
}
function renderOne(res, fav) {
res.format({
html: () => res.render('favourite.dust', fav),
json: () => res.send(fav)
});
}
router.get('/', (req, res) => {
renderAll(res, req.app.locals.favourites);
});
router.get('/:id', (req, res) => {
const id = parseInt(req.params.id);
const fav = req.app.locals.favourites.filter(e => e._id === id)[0];
if (fav) {
renderOne(res, fav);
} else {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('Not found');
}
});
router.get('/search', (req, res) => {
const filtered = req.app.locals.favourites.filter(e => {
for (const k in req.query) {
if (k != 'dataURL' && req.query[k] != e[k]) {
return false;
}
}
return true;
});
renderAll(res, filtered);
});
router.put('/:id', (req, res) => {
const edit = req.app.locals.favourites
.find(e => e._id === parseInt(req.params.id));
if (!edit) {
createFav(req, res);
} else {
for (const key of ['dataURL', 'name']) {
if (req.body[key]) {
edit[key] = req.body[key];
} else {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('Bad PUT form parameters');
return;
}
}
edit.bookmarked = !!req.params.bookmarked;
req.app.locals.writeFavs();
res.status = 200;
renderOne(res, edit);
}
});
router.delete('/:id', (req, res) => {
let idx = -1;
const id = parseInt(req.params.id);
for (let i = 0; i < req.app.locals.favourites.length; i++) {
if (req.app.locals.favourites[i]._id === id) {
idx = i;
break;
}
}
if (idx == -1) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Favourite not found');
return;
} else {
req.app.locals.favourites.splice(idx, 1);
req.app.locals.writeFavs();
res.format({
json: () => res.writeHead(202),
html: () => res.writeHead(302, { 'Location': '/favourites' })
});
res.end();
}
});
/** router for /root */
module.exports = router;