<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Gerard Rovira on Medium]]></title>
        <description><![CDATA[Stories by Gerard Rovira on Medium]]></description>
        <link>https://medium.com/@zurfyx?source=rss-b8ea10459b05------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*K19tf5An02W6cyBFtBjwwg.jpeg</url>
            <title>Stories by Gerard Rovira on Medium</title>
            <link>https://medium.com/@zurfyx?source=rss-b8ea10459b05------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 19:50:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zurfyx/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Android Travis CI with Autodeploy (API 26+)]]></title>
            <link>https://medium.com/@zurfyx/android-travis-ci-with-autodeploy-api-26-efb6c1863628?source=rss-b8ea10459b05------2</link>
            <guid isPermaLink="false">https://medium.com/p/efb6c1863628</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[travis-ci]]></category>
            <dc:creator><![CDATA[Gerard Rovira]]></dc:creator>
            <pubDate>Thu, 02 Nov 2017 00:01:33 GMT</pubDate>
            <atom:updated>2017-11-03T07:42:10.731Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U62uxIOclJe-Lyre14p_rQ.png" /></figure><p><a href="https://github.com/zurfyx/travis-android">[Example repository]</a></p><p>Hello there!</p><p>Given that setting up Travis to work with Android is such a pain[<a href="https://github.com/travis-ci/travis-ci/issues/7425.">1</a>][<a href="https://github.com/travis-ci/travis-ci/issues/8188">2</a>][<a href="https://github.com/bitrise-steplib/steps-create-android-emulator/issues/13">3</a>][<a href="https://github.com/OneBusAway/onebusaway-android/issues/228">4</a>], I thought I could share my little knowledge to newcomers after having spent a day digging through tutorials to get my project working. This article is meant to be a more complete version of my <a href="https://stackoverflow.com/a/47064652/2013580">StackOverflow reply</a>.</p><p>One of the users who I’ve come across the most when looking up for information was <a href="https://stackoverflow.com/users/937715/sean-barbeau">Sean Barbeau</a>, who pretty much <a href="https://github.com/OneBusAway/onebusaway-android/commit/03e262d2ca17e2b4ea654640b38d9719bb8e9a3d">considered it impossible</a> to emulate as it was done in the past.</p><p>Prior API 24, it did work by installing the proper Android Emulators. For those who’s not in their interest to update to the latest API versions, I suggest you to read <a href="https://medium.com/@harmittaa/travis-ci-android-example-357f6e632fc4">Travis CI Android Example</a> and <a href="http://szagurskii.com/blog/how-to-deploy-apk-to-github-releases-with-travis-ci/">How to Deploy APK to GitHub releases with Travis CI</a>. They are both excellent articles.</p><p><em>I assume that you know at least the very basics of Travis CI, such as how to enable it. Otherwise you might want to head over the </em><a href="https://docs.travis-ci.com/user/getting-started/"><em>Getting Started</em></a><em> tutorial first.</em></p><p>Let’s start. What’s the problem?</p><p>— API 24+ Android emulators do not work with Travis CI (<a href="https://github.com/travis-ci/travis-ci/issues/8188#issue-246612396">this</a> should be an OK configuration).</p><p>An acceptable solution seems to be using gradlew to run the application tests instead of adb emulator. It seems to have some limitation, but <a href="https://developer.android.com/studio/test/command-line.html#RunTestsDevice">it should work</a>. Credits to <a href="https://github.com/pockethub/PocketHub">PocketHub</a>.</p><h3>Automatic tests</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fEDiDVqLKouPuZ3Gwwt-qQ.png" /></figure><p>Having said that we have to use gradlew , let’s see how the solution actually looks like for running the application tests only.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da17632660225bf131e2f7b69287b9fd/href">https://medium.com/media/da17632660225bf131e2f7b69287b9fd/href</a></iframe><p><strong>Relevant stuff:</strong></p><ul><li>before_cache and cache is optional, but it will speed up our runs by reusing previously downloaded dependencies. Recommended by Travis on <a href="https://docs.travis-ci.com/user/languages/android/#Caching">their documentation</a>.</li><li>env your application API numbers go here. We’ll get into that in a second¹.</li><li>components Android must-have requirements on the system.</li><li>script What we want to evaluate. In this case we want Travis to run our tests and also make sure that the application can be built correctly. We will later use the built application as our release artifact.</li></ul><p>¹<strong>Environment variables that you might have to adapt</strong> to your project ones:</p><p>Some information should be available either in the build.gradle or AndroidStudio -&gt; Settings -&gt; Android SDK -&gt; SDK Tools</p><p>(if you’re building a new project with an updated AndroidStudio you should just pick the latest versions in the following links)</p><p><strong>ANDROID_API</strong>: <a href="https://developer.android.com/guide/topics/manifest/uses-sdk-element.html#ApiLevels">https://developer.android.com/guide/topics/manifest/uses-sdk-element.html#ApiLevels</a></p><p><strong>ANDROID_BUILD_TOOLS</strong>: <a href="https://developer.android.com/studio/releases/build-tools.html">https://developer.android.com/studio/releases/build-tools.html</a></p><h3>Automatic tests + deployment to GitHub Releases</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9hxMQCWbZuk4qm4psxYYqw.png" /></figure><p>Deployment can be done anywhere once we have the artifact ready (that is the APK that we want to publish). For most cases, the most cumbersome process is the generation of the signed APK. Later, you can adapt it to deploy it to somewhere else by following a similar strategy.</p><p>What we want to do now is: have our latest master version deploy as a latest release. Generating a different one per commit once we have this set up is trivial, but I believe that this would lead to an insane amount of releases (which we would probably prefer to cherry-pick by ourselves instead).</p><p>Let’s see the resulting .travis.yml file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6683dde60a44c847e43104c911a2e0e/href">https://medium.com/media/d6683dde60a44c847e43104c911a2e0e/href</a></iframe><p>First thing you will notice is that we <strong>now have three more environment variables</strong> (the x3 secure).</p><p>These are the (1) keystore password, (2) key password and (3) GitHub API keys encrypted.</p><p>(1) and (2). AndroidStudio -&gt; Build -&gt; Generate Signed APK -&gt; Create new</p><p>The keystore path should be the root folder of your project (I named it keystore.jks).</p><p>First password is the keystore password, second one is the key password. Note them down.</p><p>To obtain a encrypted version, run travis encrypt storepass=password_here and travis encrypt keypass=password_here .</p><p>(3). GitHub <a href="https://github.com/settings/tokens/new">New Token</a>. Check repo (full control of private repositories)</p><p>Encrypt that as well travis encrypt GH_TOKEN=token_here . We’ll be reusing that token later. Don’t lose it.</p><p>For the before_deploy part, we’ll need a encrypted version of keystore.jks. You must not upload that on GitHub.</p><pre>travis encrypt-file keystore.jks</pre><p><em>If you are not logged in to Travis it will promp </em><em>not logged in — try running travis login --org. You can reuse the GitHub token we generated before to do so.</em></p><pre><em>travis login --github-token your_token_here</em></pre><p><em>We will still need this token one more time.</em></p><p>It should generate a keystore.jks.enc which is the encrypted version. You have to upload this one. Make sure to add keystore.jks to your .gitignore or move that file away from that folder now.</p><p>It should also return you a line of code like the following: openssl aes-256-cbc -K ... Replace the first before_deploy line with this one.</p><p>For your information, what we do next is to sign the built APK (from the scripts part) with the keystore information we just generated. It then verifies it, and zipaligns it (which is pretty much about optimizing it for production use).</p><p>You might have to change the alias name on the first jarsigner command line (that is the last parameter). To find out your the alias you set earlier you can use the following command:</p><pre>keytool -keystore keystore.jks -list -v</pre><p>Now, you have to copy-paste the following file into scripts/tag.sh</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db0361a84f689cdf56ba3b366370d6ac/href">https://medium.com/media/db0361a84f689cdf56ba3b366370d6ac/href</a></iframe><p>Give it execution permissions: chmod +x scripts/tag.sh</p><p>What we do here is to create a tag to the latest commit on the master branch history. We’re basically saying that the latest commit hash is aliased to the latest name, which will make it appear on the releases GitHub tab.</p><p>Since we are reusing the latest name in every build, we have to delete and recreate the tag every time to have the time updated.</p><p>Note that we are not updating any artifact in here, we are simply mapping a commit hash with a name.</p><p>Lastly, going back to the .travis.yml file, we have the deploy part.</p><p>This one is the responsible for uploading the signed APK we generated earlier.</p><p>Since the deploy is already handled by Travis, we just need to pass it in a GitHub API Key (encrypted of course). In this step you might want to reuse the API key we created last in <a href="https://github.com/settings/tokens/new">here</a>.</p><p>Encrypt it like this travis encrypt token_here . Note that this time we don’t have GH_TOKEN environment variable name in front.</p><p>The result of which has to be written in the secure part of the deploy.</p><p>Two relevant flags to notice:</p><p>overwrite : since the latest tag will be reused, we want the APK to be rewritten every time.</p><p>skip_cleanup : we don’t want artifacts to be removed before deploying.</p><p>And that’s it! You should now have Travis autodeploying your Android project.</p><h3>Automatic tests + deployment to somewhere else</h3><p>Since there are endless possibilities, I won’t go in depth with this.</p><p>If you’ve fully read the previous deployment to GitHub Releases instructions, you will notice that you may just have to change the deploy part of the .travis.yml , and maybe remove the scripts/tag.sh line and file.</p><p>Signing the APK has to be done either way if you want your APK to be delivered to someone else but the development team.</p><p>You can check the example repository <a href="https://github.com/zurfyx/travis-android">here</a>.</p><p><em>Have any questions? Please, let me know in the comments.</em></p><p><em>You can also get in touch with me via </em><a href="https://twitter.com/_zurfyx"><em>Twitter</em></a><em>, </em><a href="https://www.linkedin.com/in/gerard-rovira"><em>LinkedIn</em></a><em>, </em><a href="https://github.com/zurfyx"><em>GitHub</em></a><em>, </em><a href="http://stackoverflow.com/users/2013580/zurfyx"><em>StackOverflow</em></a><em>or Mail.</em></p><p><em>Mail: bWFpbHRvOnp1cmZ5eEBnbWFpbC5jb20=</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efb6c1863628" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a scalable Node.js Express app]]></title>
            <link>https://medium.com/@zurfyx/building-a-scalable-node-js-express-app-1be1a7134cfd?source=rss-b8ea10459b05------2</link>
            <guid isPermaLink="false">https://medium.com/p/1be1a7134cfd</guid>
            <category><![CDATA[mongoose]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Gerard Rovira]]></dc:creator>
            <pubDate>Mon, 13 Feb 2017 15:48:27 GMT</pubDate>
            <atom:updated>2017-02-13T18:42:27.510Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WHMoBw40Ed3zp2yNDksoyw.png" /></figure><p>This publication was initially a <a href="http://stackoverflow.com/a/42164174/2013580">response</a> to <a href="http://stackoverflow.com/questions/41875617/building-enterprise-app-with-node-express/">how to properly isolate a controller using Node.js Express</a> application. Since the community response was so positive I thought I might as well adapt my answer to make it my first publication on Medium. :-)</p><p>It is assumed that you have already worked with <a href="https://expressjs.com/en/4x/api.html">Express 4</a> and <a href="http://mongoosejs.com/">Mongoose</a>, and have general knowledge about JavaScript and Node.js.</p><p>Neither folder structure nor Express setup are included. But I will consider writing about my whole Node.js setup if you enjoyed this article! <em>let me know in the comments below</em></p><h3>The real problem behind starter Node.js tutorials</h3><p>Most Node.js <a href="https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4">t</a><a href="https://www.tutorialspoint.com/nodejs/nodejs_restful_api.htm">u</a><a href="http://adrianmejia.com/blog/2014/10/01/creating-a-restful-api-tutorial-with-nodejs-and-mongodb/">t</a><a href="https://stormpath.com/blog/tutorial-build-rest-api-mobile-apps-using-node-js">o</a><a href="https://devcenter.heroku.com/articles/mean-apps-restful-api">r</a><a href="http://cwbuecheler.com/web/tutorials/2014/restful-web-app-node-express-mongodb/">i</a><a href="http://mherman.org/blog/2016/03/13/designing-a-restful-api-with-node-and-postgres/">a</a><a href="https://codeforgeek.com/2015/08/restful-api-node-mongodb/">l</a><a href="https://pixelhandler.com/posts/develop-a-restful-api-using-nodejs-with-express-and-mongoose">s</a>, which <strong>none of them are to blame for</strong>, focus on the content: getting certain libraries / frameworks working. To make it easier for the readers who are new to them they are often presented the most simple solutions.</p><p>Whilst these solutions suit most of the times for small to medium projects, large applications tend to require far more abstraction, which is what we’ll be analyzing next.</p><p>Let’s start with a small hypothetical case:</p><ul><li>I want to have an API that serves an user search through AJAX.</li><li>I want to have an API that also serves the same user search through Socket.io.</li></ul><p>Let’s start with Express. That’s easy peasy, isn’t it?</p><p>routes.js</p><pre>import * as userControllers from &#39;controllers/users&#39;;<br>router.get(&#39;/users/:username&#39;, userControllers.getUser);</pre><p>controllers/user.js</p><pre>import User from &#39;../models/User&#39;;<br>function getUser(req, res, next) {<br>  const username = req.params.username;<br>  if (username === &#39;&#39;) {<br>    return res.status(500).json({ error: &#39;Username can\&#39;t be blank&#39; });<br>  }<br>  try {<br>    const user = await User.find({ username }).exec();<br>    return res.status(200).json(user);<br>  } catch (error) {<br>    return res.status(500).json(error);<br>  }<br>}</pre><p>Now let’s do the Socket.io part:</p><p><em>Since we’re not here to talk about </em><a href="http://socket.io/"><em>socket.io</em></a><em>, I’ll skip the boilerplate.</em></p><pre>import User from &#39;../models/User&#39;;<br>socket.on(&#39;RequestUser&#39;, (data, ack) =&gt; {<br>  const username = data.username;<br>  if (username === &#39;&#39;) {<br>    ack ({ error: &#39;Username can\&#39;t be blank&#39; });<br>  }<br>  try {<br>    const user = User.find({ username }).exec();<br>    return ack(user);<br>  } catch (error) {<br>    return ack(error);<br>  }<br>});</pre><p>We’re done! However, something smells here…</p><ul><li>if (username === &#39;&#39;). We had to write the controller validator twice. What if there were ncontroller validators? Would we have to keep two (or more) copies of each up to date?</li><li>User.find({ username }) is repeated twice. That could possibly be a service.</li></ul><p>We have just written two controllers that are attached to the exact definitions of Express and Socket.io respectively. They will most likely never break during their lifetime because both Express and Socket.io tend to have backwards compatibility. <strong>BUT</strong>, they are not reusable. Changing Express for <a href="https://www.npmjs.com/package/hapi">Hapi</a>? You will have to redo all your controllers.</p><p>Another bad smell that might not be so obvious…</p><p>The controller response is handcrafted. .json({ error: whatever })</p><p>APIs in RL are constantly changing. In the future you might want your response to be { err: whatever } or maybe something more complex (and useful) like: { error: whatever, status: 500 }</p><h3>Let’s get started (a possible solution)</h3><p>I can’t call it <em>the</em> solution because there is an endless amount of solutions out there. It is up to your creativity, and your needs. The following is a decent solution; I’m using it in a relatively large project and it seems to be working well, and it fixes everything I pointed out before.</p><p>I’ll go Model -&gt; Service -&gt; Controller -&gt; Router, to keep it interesting until the end.</p><h4>Model</h4><p>Although I won’t go into details about the Model, you should be having a similar <a href="http://mongoosejs.com/docs/models.html">Mongoose Model</a> structure.</p><p>models/User/validate.js</p><pre>export function validateUsername(username) {<br>  return true;<br>}</pre><p>You can read more about the appropriate structure for mongoose 4.x validators <a href="http://stackoverflow.com/a/42116795">here</a>.</p><p>models/User/index.js</p><pre>import { validateUsername } from &#39;./validate&#39;;</pre><pre>const userSchema = new Schema({<br>  username: { <br>    type: String, <br>    unique: true,<br>    validate: [{ validator: validateUsername, msg: &#39;Invalid username&#39; }],<br>  },<br>}, { timestamps: true });</pre><pre>const User = mongoose.model(&#39;User&#39;, userSchema);</pre><pre>export default User;</pre><p>This is just a basic User Schema with an username field and created updated mongoose-controlled fields.</p><p>The reason why I included the validate field here is for you to notice that you should be doing most model validation in here, not in the controller.</p><p>Mongoose Schema is the last step before reaching the database, unless someone queries MongoDB directly you will always rest assured that everyone goes through your model validations, which gives you more security than placing them on your controller. Not to say that unit testing validators as they are in the previous example is trivial.</p><p>Read more about this <a href="http://stackoverflow.com/questions/20465414/best-place-to-handle-data-validation-with-mongoose-and-express">here</a> and <a href="https://thecodebarbarian.wordpress.com/2013/06/06/61/">here</a>.</p><h3>Service</h3><p>The service will act as the processor. Given acceptable parameters, it’ll process them and return a value.</p><p>Most of the times (including this one), it’ll make use of <a href="http://mongoosejs.com/docs/models.html">Mongoose Models</a> and return a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a> (or a callback; but <a href="http://callbackhell.com/">I would definitely</a> use ES6 with Promises if you are not doing so already).</p><p>services/user.js</p><pre>function getUser(username) {<br>  return User.find({ username}).exec(); // Just as a mongoose <br>                                        // reminder, .exec() on find<br>                                        // returns a Promise instead<br>                                        // of the default callback.<br>}</pre><p>At this point you might be wondering, no catch block? Nope, because we&#39;re going to do a <em>cool trick</em> later and we don&#39;t need a custom one for this case.</p><p>Other times, a trivial sync service will suffice. Make sure your sync service never includes I/O, otherwise you will be blocking <a href="http://stackoverflow.com/questions/17959663/why-is-node-js-single-threaded">the whole Node.js thread</a>.</p><p>services/user.js</p><pre>function isChucknorris(username) {<br>  return username === &#39;Chuck Norris&#39;;<br>}</pre><h3>Controller</h3><p>We want to avoid duplicated controllers, so we’ll only have <strong>a</strong> controller for each action.</p><p>controllers/user.js</p><pre>export function getUser(username) {<br>}</pre><p>How does this signature look like now? Pretty, right? Because we’re only interested in the username parameter, we don’t need to take useless stuff such as req, res, next.</p><p>Let’s add in the missing validators and service:</p><p>controllers/user.js</p><pre>import { getUser as getUserService } from &#39;../services/user.js&#39;</pre><pre>function getUser(username) {<br>  if (username === &#39;&#39;) {<br>    throw new Error(&#39;Username can\&#39;t be blank&#39;);<br>  }<br>  return getUserService(username);<br>}</pre><p>Still looks neat, but… what about the throw new Error, won&#39;t that make my application crash? - Shh, wait. We&#39;re not done yet.</p><p>So at this point, our controller documentation would look sort of:</p><pre>/**<br> * Get a user by username.<br> * @param username a string value that represents user&#39;s username.<br> * @returns A Promise, an exception or a value.<br> */</pre><p><em>What’s the “value” stated in the </em><em>returns? Remember that earlier we said that our services can be both sync or async (using </em><em>Promise)? </em><em>getUserService is async in this case, but </em><em>isChucknorris service wouldn&#39;t, so it would simply return a value instead of a Promise.</em></p><p>Hopefully everyone will read the docs. Because they will need to treat some controllers different than others, and some of them will require a try-catch block.</p><p>Since we can’t trust developers (this includes me) reading the docs before trying first, at this point we have to make a decision:</p><ul><li>Controllers to force a Promise return</li><li>Service to always return a Promise</li></ul><p><em>⬑ This will solve the inconsistent controller return (not the fact that we can omit our try-catch block).</em></p><p>IMO, I prefer the first option. Because controllers are the ones which will chain the most Promises most of the times.</p><pre>return findUserByUsername<br>         .then((user) =&gt; getChat(user))<br>         .then((chat) =&gt; doSomethingElse(chat))</pre><p>If we are using ES6 Promise we can make use of a nice property of Promise to do so: Promisecan handle non-promises during their lifespan and still keep returning a Promise:</p><pre>return promise<br>         .then(() =&gt; nonPromise)<br>         .then(() =&gt; // I can keep on with a Promise.</pre><p>If the only service we call doesn’t use Promise, we can make one ourselves.</p><pre>return Promise.resolve() // Initialize Promise for the first time.<br>  .then(() =&gt; isChucknorris(&#39;someone&#39;));</pre><p>Going back to our example it would result in:</p><pre>...<br>return Promise.resolve()<br>  .then(() =&gt; getUserService(username));</pre><p>We don’t actually need Promise.resolve() in this case as getUserService already returns a Promise, but we want to be consistent.</p><p><em>If you are wondering about the </em><em>catch block: we don&#39;t want to use it in our controller unless we want to do it a custom treatment. This way we can make use of the two already built-in communication channels (the exception for errors and return for success messages) to deliver our messages through individual channels.</em></p><p>Instead of ES6 Promise .then, we can alternatively make use of the newer ES2017 async / await (<a href="http://www.2ality.com/2016/02/ecmascript-2017.html">now official</a>) in our controllers:</p><pre>async function myController() { <br>  const user = await findUserByUsername(); <br>  const chat = await getChat(user);<br>  const somethingElse = doSomethingElse(chat); <br>  return somethingElse; <br>}</pre><p><em>Notice </em><em>async in front of the </em><em>function.</em></p><h3>Router</h3><p>Finally the router, yay!</p><p>So we haven’t responded anything to the user yet, all we have is a controller that we know that it ALWAYS returns a Promise (hopefully with data). Oh!, and that can possibly throw an exception if throw new Error is called or some service Promise breaks.</p><p>The router will be the one that will, in an uniform way, control petitions and return data to clients, be it some existing data, null or undefined data or an error.</p><p>Router will be the ONLY one that will have multiple definitions. The number of which will depend on our interceptors. In the hypothetical case these were API (with Express) and Socket (with Socket.io).</p><p>Let’s review what we have to do:</p><p>We want our router to convert (req, res, next) into (username). A naive version would be something like this:</p><pre>router.get(&#39;users/:username&#39;, (req, res, next) =&gt; {<br>  try {<br>    const result = await getUser(req.params.username); // Remember: getUser is the controller.<br>    return res.status(200).json(result);<br>  } catch (error) {<br>    return res.status(500).json(error);<br>  }<br>});</pre><p>Although it would work well, that would result in a huge amount of code duplication if we copy-pasted this snippet in all our routes. So we have to make a better abstraction.</p><p>In this case, we can create a sort of fake router client that takes a promise and n parameters and does its routing and return tasks, just like it would do in each of the routes.</p><pre>/**<br> * Handles controller execution and responds to user (API Express version).<br> * Web socket has a similar handler implementation.<br> * @param promise Controller Promise. I.e. getUser.<br> * @param params A function (req, res, next), all of which are optional<br> * that maps our desired controller parameters. I.e. (req) =&gt; [req.params.username, ...].<br> */<br>const controllerHandler = (promise, params) =&gt; async (req, res, next) =&gt; {<br>  const boundParams = params ? params(req, res, next) : [];<br>  try {<br>    const result = await promise(...boundParams);<br>    return res.json(result || { message: &#39;OK&#39; });<br>  } catch (error) {<br>    return res.status(500).json(error);<br>  }<br>};<br>const c = controllerHandler; // Just a name shortener.</pre><p>If you are interested in knowing more about this <em>trick</em>, you can read about the full version of this in my other reply in <a href="http://stackoverflow.com/questions/37876889/react-redux-and-websockets-with-socket-io/41309189#41309189">React-Redux and Websockets with socket.io</a> (“SocketClient.js” section).</p><p>How would your route look like with the controllerHandler?</p><pre>router.get(&#39;users/:username&#39;, c(getUser, (req, res, next) =&gt; [req.params.username]));</pre><p>A clean one line, just like in the beginning.</p><h3>Further optional steps</h3><h4>Controller Promises</h4><p>It only applies to those who use ES6 Promises. ES2017 async / await version already looks good to me.</p><p>For some reason, I dislike having to use Promise.resolve() name to build the initialize Promise. It&#39;s just not a clear what&#39;s going on there.</p><p>I’d rather replace them for something more understandable:</p><pre>const chain = Promise.resolve(); // Write this as an external imported variable or a global.</pre><pre>chain<br>  .then(() =&gt; ...)<br>  .then(() =&gt; ...)</pre><p>Now you know that chain marks the start of a chain of Promises. So does everyone who reads your code, or if not, they at least assume it&#39;s a chain a service functions.</p><h4>Express error handler</h4><p>Express does have a default error handler which you should be using to capture at least the most unexpected errors.</p><pre>router.use((err, req, res, next) =&gt; {<br>  // Expected errors always throw Error.<br>  // Unexpected errors will either throw unexpected stuff or crash the application.<br>  if (Object.prototype.isPrototypeOf.call(Error.prototype, err)) {<br>    return res.status(err.status || 500).json({ error: err.message });<br>  }</pre><pre>  console.error(&#39;~~~ Unexpected error exception start ~~~&#39;);<br>  console.error(req);<br>  console.error(err);<br>  console.error(&#39;~~~ Unexpected error exception end ~~~&#39;);<br></pre><pre>  return res.status(500).json({ error: &#39;⁽ƈ ͡ (ुŏ̥̥̥̥םŏ̥̥̥̥) ु&#39; });<br>});</pre><p>What’s more, you should probably be using something like <a href="https://www.npmjs.com/package/debug">debug</a> or <a href="https://www.npmjs.com/package/winston">winston</a> instead of console.error, which are more professional ways to handle logs.</p><p>And that’s is how we plug this into the controllerHandler:</p><pre>...<br>  } catch (error) {<br>    return res.status(500) &amp;&amp; next(error);<br>  }</pre><p>We are simply redirecting any captured error to Express’ error handler.</p><h4>Error as ApiError</h4><p>Error is considered the default class to encapsulate errors in when throwing an exception in Javascript. If you really only want to track your own controlled errors, I&#39;d probably change the throw Error and the Express error handler from Error to ApiError, and you can even make it fit your needs better by adding it the status field.</p><pre>export class ApiError {<br>  constructor(message, status = 500) {<br>    this.message = message;<br>    this.status = status;<br>  }<br>}</pre><h3>Additional information</h3><h4>Custom exceptions</h4><p>You can throw any custom exception at any point by throw new Error(&#39;whatever&#39;) or by using new Promise((resolve, reject) =&gt; reject(&#39;whatever&#39;)). You just have to play with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a>.</p><h4>ES6 ES2017</h4><p>That’s very opinionated point. IMO <a href="http://es6-features.org/">ES6</a> (or even <a href="http://www.2ality.com/2016/02/ecmascript-2017.html">ES2017</a>, now having an official set of features) is the appropriate way to work on big projects based on Node.</p><p>If you aren’t using it already, try looking at <a href="http://es6-features.org/">ES6</a> features and <a href="http://www.2ality.com/2016/02/ecmascript-2017.html">ES2017</a> and <a href="https://babeljs.io/">Babel</a> transpiler.</p><h3>Result</h3><p>The complete code (shown before step-by-step), with no comments or annotations. You can check everything regarding this code by scrolling up to the appropriate section.</p><p>router.js</p><pre>const controllerHandler = (promise, params) =&gt; async (req, res, next) =&gt; {<br>  const boundParams = params ? params(req, res, next) : [];<br>  try {<br>    const result = await promise(...boundParams);<br>    return res.json(result || { message: &#39;OK&#39; });<br>  } catch (error) {<br>    return res.status(500) &amp;&amp; next(error);<br>  }<br>};<br>const c = controllerHandler;</pre><pre>router.get(&#39;/users/:username&#39;, c(getUser, (req, res, next) =&gt; [req.params.username]));</pre><p>controllers/user.js</p><pre>import { serviceFunction } from service/user.js<br>export async function getUser(username) {<br>  const user = await findUserByUsername();<br>  const chat = await getChat(user);<br>  const somethingElse = doSomethingElse(chat);<br>  return somethingElse;<br>}</pre><p>services/user.js</p><pre>import User from &#39;../models/User&#39;;<br>export function getUser(username) {<br>  return User.find({}).exec();<br>}</pre><p>models/User/index.js</p><pre>import { validateUsername } from &#39;./validate&#39;;</pre><pre>const userSchema = new Schema({<br>  username: { <br>    type: String, <br>    unique: true,<br>    validate: [{ validator: validateUsername, msg: &#39;Invalid username&#39; }],<br>  },<br>}, { timestamps: true });</pre><pre>const User = mongoose.model(&#39;User&#39;, userSchema);</pre><pre>export default User;</pre><p>models/User/validate.js</p><pre>export function validateUsername(username) {<br>  return true;<br>}</pre><p><em>Have any questions? Please, let me know in the comments.</em></p><p><em>You can also get in touch with me via </em><a href="https://twitter.com/_zurfyx"><em>Twitter</em></a><em>, </em><a href="https://www.linkedin.com/in/gerard-rovira"><em>LinkedIn</em></a><em>, </em><a href="https://github.com/zurfyx"><em>GitHub</em></a><em>, </em><a href="http://stackoverflow.com/users/2013580/zurfyx"><em>StackOverflow</em></a><em> or Mail.</em></p><p><em>Mail: bWFpbHRvOnp1cmZ5eEBnbWFpbC5jb20=</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1be1a7134cfd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>