REST routing

En startpunkt för dagens genomgång och övningar:

Starting point app (REST)

Ett exempel på en färdig router klass med POST, GET, PUT, DELETE


'use strict'; var s = g.settings; module.exports = class REST { constructor(express) { this.settings = s.REST; this.DB = new g.classes.DB(); // DB connection & models this.app = express; this.router(); } // setup standard CRUD for route router() { var me = this; //['GET','PUT','..'] , any_route, request this.app.all(this.settings.route, function(req, res) { var model = me.DB.getModel(req.params.model); // do we have a 404? if (!me[req.method] || !model) { res.sendStatus(404); res.end(); return; } // this.GET (Apple, {id:4}, {}, req, res) me[req.method](model, req.params, req.body, req, res); }); } // CREATE // (Apple, ..) POST(model, params, body, req, res) { var me = this, toSave = new model(body); // new model instance with data // write data to DB toSave.save(function(err, result) { if (err) { me.error(err, res); return; } res.json(result); // respond with result }); } // READ // (Apple, {id: 4}, ..) GET(model, params, body, req, res) { // pick a mongoose query function and parameters for it var me = this, func = params.modelID ? 'findById' : 'find', q = params.modelID ? params.modelID : {}; // call the query function (find || findById) model[func](q, function(err, result) { if (err) { me.error(err, res); return; } res.json(result); // respond with result }); } // UPDATE // (Apple, {id: 4}, ..) PUT(model, params, body, req, res) { if (!params.modelID) { this.error({error: 'Missing ID!'}, res); return; } var me = this; model.findByIdAndUpdate(params.modelID, body, {new: true}, function (err, result) { if (err) { me.error(err, res); return; } res.json(result); // respond with result }); } // DELETE // (Apple, {id: 4}, ..) DELETE(model, params, body, req, res) { if (!params.modelID) { this.error({error: 'Missing ID!'}, res); return; } var me = this; model.findByIdAndRemove(params.modelID, function(err, result) { if (err) { me.error(err, res); return; } res.json(true); // respond with result }); } error(err, res) { res.status(400); res.json(err); } };
0 votes