You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Express REST resources as middleware, mountable anywhere.
Usage
In ES6
importresourcefrom'resource-router-middleware';exportdefaultresource({mergeParams: true,id : 'user',load(req,id,callback){varuser=users.find(user=>user.id===id),err=user ? null : 'Not found';callback(err,user);},list({ params },res){res.json(users);},create({ body },res){body.id=users.length.toString(36);users.push(body);res.json(body);},read({ user },res){res.json(user);},update({ user, body },res){for(letkeyinbody){if(key!=='id'){user[key]=body[key];}}res.status(204).send();},delete({ user },res){users.splice(users.indexOf(user),1);res.status(204).send();}});
In ES5
varresource=require('resource-router-middleware');varusers=[];module.exports=resource({mergeParams: true,/** Property name to store preloaded entity on `request`. */id : 'user',/** For requests with an `id`, you can auto-load the entity. * Errors terminate the request, success sets `req[id] = data`. */load : function(req,id,callback){varuser=users.filter(function(user){returnuser.id===id;})[0];if(!user){callback('Not found');}else{callback(null,user);}},/** GET / - List all entities */list : function(req,res){res.json(users);},/** POST / - Create a new entity */create : function(req,res){varuser=req.body;user.id=users.length.toString(36);users.push(user);res.json(user);},/** GET /:id - Return a given entity */read : function(req,res){res.json(req.user);},/** PUT /:id - Update a given entity */update : function(req,res){varid=req.params[this.id];for(vari=users.length;i--;){if(users[i].id===id){users[i]=req.body;users[i].id=id;returnres.status(204).send('Accepted');}}res.status(404).send('Not found');},/** DELETE /:id - Delete a given entity */delete : function(req,res){varid=req.params[this.id];for(vari=users.length;i--;){if(users[i].id===id){users.splice(i,1);returnres.status(200);}}res.status(404).send('Not found');}});
About
🚴 Express REST resources as middleware mountable anywhere