nodejs + express + rest api + promises with a nice express middleware

Ok, so I recently worked on a project with a NodeJs and Express backend. The entire backend was a promise based api, which has its niceties as well as its annoyances. The nice thing is the .then() syntax which is now fairly standard in the world of javascript, but.. imo the promise api’s are fairly verbose, especially when you want to standardise your json output, for example imagine this for a simple route to update a username:

Now imagine building 20+ routes to your application and having to write a promise handler for each response, it would take a while. Not to mention a bitch to manage.

Enter the express middleware:

With using the above middleware in the server.js (or where ever you setup your express server), we have injected 3 functions into res which is now automatically available to each routing file. The 1st 2 functions are fairly self explanatory, res.jsonSuccess merely passes success is true and the data passed and fail doing pretty much the same thing.

The res.jsonPromise is a little different, the parameter passed is the function that you were expecting a promise from (for example the first snippet of code at the top) and it just passes the success and fail functions as the 1st and 2nd param.

The result being:

The function:

Simply returns a promise in the form of then(). Due to the beauty of Javascript, the then() function is just one of the available functions returned in the promise, and one we can call in our middleware.

So by using a simple 3 function middleware I normalised the output of the API and reduced a 13 simple line routing handle to 3 lines.