Wednesday, 1 March 2017

Please rate and help me improve my API design

Hi guys, so lately I've been trying to focus on improving how I make APIs using Node/Express, and while I think "I'm getting there", I'd really like a few pointers and general feedback on what I'm doing wrong and what I'm doing right.Here's an overview, the code mostly consists of these several files:routes > users.js (PIC: http://ift.tt/2lVkV9z)controllers -> users.js (PIC: http://ift.tt/2ltdtiy)helpers -> routeHelpers.js (PIC: http://ift.tt/2lVpO2F)Now to explain a few things:1) The general idea of mine is use the files inside routes folder, in this example users.js (first pic) is one such file, as a general overview of API's endpoints.2) Here I'll be able to see the flow of "checking for things", which could be anything from validating body/params/query to checking whether user is logged in/is owner of some object before I can pass the command to controller to actually do the work.3) While the checking is happening, for example validating params/body, I save the validated values inside req.values, so that I can later access them inside controller (see pic 3) - take a look at req.values.params.userId (note it says req.values.params.id, but I tweaked code later, so it should say req.values.params.userId, as that's the name I've given it inside routes file).So, thanks to all of that, once I'm inside a controller, I've abstracted away all the validation/authentication/authorization and because of that controller's functions are much more thinner.The cons from what I could tell:1) The middleware array inside routes files can get pretty long, say I need to validate 2 params, a body, check whether user is authenticated and do authorization.2) As I've split the code inside 3 separate location, working on it, at times, can require me jumping all over the place.The pros from what I could tell:1) Organization2) Huge Once I'm inside a controller, I already know everything is validated etc and can focus on business logic.Any feedback? Thanks!

Submitted March 01, 2017 at 11:05PM by eXtremeRR

No comments:

Post a Comment