Last active
December 24, 2015 11:09
-
-
Save zekenie/6788991 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//[normal webapp routes here] | |
var apiAuth = function(req,res,next) { | |
///... | |
req.api = true; | |
//... | |
next(); | |
}; | |
app.all("/api/*",apiAuth); | |
var actions = { | |
list:{ | |
POST:"create", | |
GET:"index" | |
}, | |
item:{ | |
GET:"view", | |
PUT:"update", | |
DELETE:"delete" | |
} | |
}; | |
var routeApi = function(type,req,res,next) { | |
var action = actions[type][req.method]; | |
if(!action) { | |
res.send(404); | |
return; | |
} | |
var route = models[req.param.model][action]; | |
route(req,res,next); | |
}; | |
app.all('/api/:model',function(req,res,next) { | |
routeApi('list',req,res,next); | |
}); | |
app.all('/api/:model/:id',function(req,res,next) { | |
routeApi('item',req,res,next); | |
}); | |
app.all("*",function(req,res) { | |
//make sure res and payload were defined in the route logic | |
if(res.payload && res.method) { | |
//if its an api call, we're going to want to always send json | |
if(req.api) { | |
//if its the render method, remove the first param which will be the view file | |
if(res.method === 'render') | |
res.payload.shift(); | |
res.json(res.payload); | |
return; | |
} | |
//otherwise we can proceed this way | |
res[res.method].apply(null,res.payload); | |
} else { | |
res.send(500); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment