I have a REST API for songs resources, they got an id and a title, admins can perform GET /songs/:id directly, but common users can only access through GET /songs/:title.
So if a common user tries to access to a resource like:
{ "id":9248, "title": "Hala Madrid" }
By requesting GET /songs/9248 he should be redirected to GET /songs/hala_madrid.
So I could have two different route handlers, and repeat the query. But I really don't want to query twice. So I thought I could reset url and assign the found song to req.song.
I tried setting up the following routes and implement a single get controller method:
``` router.get('/:id([0-9]+)', songs.get);
router.get('/:title', songs.get); ```
function get(req, res, next) { let { id, title} = req.params; console.log(id, title); let permalink = id || title; let field = isNaN(permalink) ? 'title' : 'id'; if (req.song) { let { song } = req; return res.render('app', {song, title: 'song', page: 'song'}); } queries.getSong(field, permalink).then(result => { let song = result[0]; if (req.session.user.role === 'user' && field === 'id') { req.song = song; req.url = `/songs/${song.title}`; return next(); } return res.render('app', {song, title: 'song', page: 'song'}); }) .catch(err => { console.error(err); return res.status(500).json({error: err}); }); }
Im a bit lost as it's ending up in unhandled error, I dont know how reload the request to be handled again
via diegoaguilar
No comments:
Post a Comment