After building quite a few APIs with Node.js and Express over the last couple years, I started forming some strong opinions about what I liked and disliked. I had gotten very familiar with the async library, and rightly so. It's a great tool for maintaining control in the face of all those callbacks. However, I was always left wanting something that felt a little more structured. I wanted a pattern, something I could lean on to standardize the way I do things. Since API routes have common high-level components (validating a request, performing an action in the database, returning a response, etc), express-classy
is my take on organizing and controlling the logic flow in Express route handlers.
Example
add_person.js:
var util = ;var CreateHandler = CreateHandler; moduleexports = AddPerson; { CreateHandler;} util; AddPersonprototype { thisreq; thisreq; var validationErrors = thisreq; if validationErrors return this; var person = firstName: thisreqbodyfirstName lastName: thisreqbodylastName ; return this; }; AddPersonprototype { // add 'person' to the database here // if error, emit "error", passing the error // if successful, emit "done", passing the data for response };
routes.js:
var express = ;var router = express;var AddPerson = ; var addPerson = ;router; moduleexports = router;