<?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 Francisco Presencia on Medium]]></title>
        <description><![CDATA[Stories by Francisco Presencia on Medium]]></description>
        <link>https://medium.com/@fpresencia?source=rss-fe52adf78e69------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*Y26or-bO1fcm7WlCWdGRJg.png</url>
            <title>Stories by Francisco Presencia on Medium</title>
            <link>https://medium.com/@fpresencia?source=rss-fe52adf78e69------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 07 Jun 2026 11:51:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fpresencia/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[Constant evolution in JS]]></title>
            <link>https://medium.com/@fpresencia/constant-evolution-in-js-af12c568f4c9?source=rss-fe52adf78e69------2</link>
            <guid isPermaLink="false">https://medium.com/p/af12c568f4c9</guid>
            <category><![CDATA[variables]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Francisco Presencia]]></dc:creator>
            <pubDate>Mon, 06 Jan 2020 15:55:19 GMT</pubDate>
            <atom:updated>2020-04-06T23:32:51.300Z</atom:updated>
            <content:encoded><![CDATA[<p>In the beginning there was <strong><em>var</em></strong>. And it weakly defining that there was something there. It was lawless and everything could be done to it:</p><pre><strong>var</strong> user <strong>=</strong> <strong>{</strong> <strong>name:</strong> <strong>&#39;</strong>Sarah<strong>&#39;,</strong> <strong>friends</strong>: <strong>[&#39;</strong>John<strong>&#39;]</strong> <strong>};</strong><br>user <strong>=</strong> null<strong>;<br></strong><em>// No error</em></pre><p>This dangerous beast had to be tamed, and the Javascript committee decided to add a variable declaration more stable, giving birth to <strong><em>let</em></strong> and <strong><em>const</em></strong>.</p><p><strong><em>const</em></strong> came to create variables that cannot be modified:</p><pre><strong>const</strong> user <strong>=</strong> <strong>{</strong> <strong>name:</strong> <strong>&#39;</strong>Sarah<strong>&#39;,</strong> <strong>friends</strong>: <strong>[&#39;</strong>John<strong>&#39;]</strong> <strong>};</strong><br>user <strong>=</strong> null<strong>;<br></strong><em>// Error </em>🎉</pre><p>But despite of its name indicating it’s a “constant”, its value can change easily:</p><pre><strong>const</strong> user <strong>=</strong> <strong>{</strong> <strong>name: &#39;</strong>Sarah<strong>&#39;,</strong> <strong>friends</strong>: <strong>[&#39;</strong>John<strong>&#39;]</strong> <strong>};</strong><br>user<strong>.</strong>name <strong>=</strong> <strong>&#39;Peter&#39;;<br></strong><em>// No error ¯\_(ツ)_/¯</em></pre><p>People were abashed and React issued strict warnings on not mutating state and everyone was busy avoiding mutating state. There was a lot to learn about this new kid on the block and devs watched many tutorials.</p><p>Of course this was not sustainable, programmers having fun and avoiding mutations? Then something better, something that makes even the deeper values not able to change was created:</p><pre><strong>&#39;use strict&#39;;<br>const</strong> user <strong>=</strong> Object.freeze<strong>({ name: &#39;</strong>Sarah<strong>&#39;, friends</strong>: <strong>[&#39;</strong>John<strong>&#39;] });</strong><br>user<strong>.</strong>name <strong>=</strong> <strong>&#39;Peter&#39;;<br></strong><em>// Error if you activate &quot;use strict&quot; </em>🎉</pre><p>“This time is for real” some people thought. And it seemed like all was good, until these fresh grads did horrible things to your -oh so- beautiful codebase and things broke in inexplicable ways.</p><p>It seemed that even if the object is defined as constant and frozen, it can still be modified if you go deep enough:</p><pre><strong>&#39;use strict&#39;;<br>const</strong> user <strong>=</strong> Object.freeze<strong>({ name: &#39;</strong>Sarah<strong>&#39;, friends</strong>: <strong>[&#39;</strong>John<strong>&#39;] });</strong><br>user.friends<strong>[</strong>0<strong>]</strong> = <strong>&#39;</strong>Tim<strong>&#39;;<br></strong><em>// No error ¯\_(ツ)_/¯</em></pre><p>And everyone was very confused and put their arms up in the air, but it was too late. So the people said “this time we will elect our own leader”!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*hp93DT_YP2RfPs7eBDtPfw.jpeg" /></figure><p>And <a href="https://immutable-js.github.io/immutable-js/">immutable</a> and <a href="https://github.com/immerjs/immer">immer</a> were born, but they of course added some overhead in what could have been a beautiful native JS.</p><p>But I decided to finally learn a bit more about CS and walk the tree. This snippet as part of my <a href="https://github.com/franciscop/statux/">React state management library <strong>Statux</strong></a>, but it’s so small that it can be shared here:</p><pre><em>// Deep freeze any object</em><br><strong>const</strong> freeze <strong>=</strong> obj <strong>=&gt; {</strong><br><em>  // Does not need freezing</em><br>  <strong>if (typeof</strong> obj<strong> !== &quot;</strong>object<strong>&quot;)</strong> return obj;</pre><pre><em>  // Already frozen</em><br>  <strong>if (</strong>Object<strong>.</strong>isFrozen<strong>(</strong>obj<strong>))</strong> <strong>return</strong> obj<strong>;</strong></pre><pre><em>  // Freeze props recursively before freezing self</em><br>  <strong>for (let</strong> key <strong>of</strong> Object<strong>.</strong>getOwnPropertyNames<strong>(</strong>obj<strong>)) {</strong><br>    <strong>if (</strong>Array.isArray<strong>(</strong>obj<strong>)</strong> <strong>&amp;&amp;</strong> key <strong>===</strong> <strong>&quot;</strong>length<strong>&quot;)</strong> <strong>continue;</strong><br>    obj<strong>[</strong>key<strong>]</strong> <strong>=</strong> <strong>typeof</strong> obj<strong>[</strong>key<strong>]</strong> <strong>=== &quot;</strong>object<strong>&quot;<br>      ?</strong> freeze<strong>(</strong>obj<strong>[</strong>key<strong>])</strong><br>      <strong>:</strong> obj<strong>[</strong>key<strong>];</strong><br>  <strong>}</strong><br>  <strong>return</strong> Object.freeze<strong>(</strong>obj<strong>)</strong>;<br><strong>};</strong></pre><p>And that’s it, now you can freeze any object you want with that snippet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*FiRnFWlEggnKFDK2Xhv5XQ.png" /></figure><pre><strong>&#39;use strict&#39;;</strong></pre><pre><em>// Using the freeze above</em><strong><br>const</strong> user <strong>=</strong> freeze<strong>({<br>  name: &#39;</strong>Sarah<strong>&#39;,<br>  friends</strong>: <strong>[&#39;</strong>John<strong>&#39;]<br>});</strong></pre><pre>user.friends<strong>[</strong>0<strong>]</strong> = <strong>&#39;</strong>Tim<strong>&#39;;<br></strong><em>// Error </em>🎉<br></pre><blockquote>This is a humorous introduction to JS constant evolution, I have nothing but deep respect for the amazing work of both the ECMAScript group and the JS community at large and love what we are building together.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af12c568f4c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debugging Bloomberg menu mimic]]></title>
            <link>https://medium.com/@fpresencia/fixing-bloomberg-menu-mimic-652cf134d493?source=rss-fe52adf78e69------2</link>
            <guid isPermaLink="false">https://medium.com/p/652cf134d493</guid>
            <category><![CDATA[debug]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Francisco Presencia]]></dc:creator>
            <pubDate>Tue, 26 Jun 2018 17:07:48 GMT</pubDate>
            <atom:updated>2018-06-26T17:14:42.921Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<p><a href="https://francisco.io/demo/bloomberg/fixed/"><strong>Working Demo</strong></a> | <a href="https://francisco.io/demo/bloomberg/broken/"><strong>Broken Demo</strong></a></p><p>Someone decided to redo a Javascript large menu into pure CSS. Looking at it and <a href="https://news.ycombinator.com/item?id=17400200">the author motivation</a> brought back memories of the time I was hacking around pure CSS components with <a href="https://picnicss.com/">Picnic CSS</a>.</p><p>But the menu is completely broken! As many cried on Hacker News. And <em>it is </em>in a sense: you cannot put the mouse over the left menu and move it over thr right one, since it will reset.</p><p>This is how pretty it looks right now so we’ll make it stay the same:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pTFxqdF5RRoqKTVzSkSKvA.png" /></figure><h3>Small visual bug/red flag</h3><p>However, <a href="https://francisco.io/demo/bloomberg/broken/">if you try to use it</a> you’ll find one of the most common issues when doing pure CSS advanced elements: <strong>links/anchor tags too small</strong>! See the target for the links:</p><blockquote>Note: this is a <strong>visual</strong> issue since we don’t want the link hover effect to disappear until the pointer crosses the line, but it doesn’t actually affect the functionality.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JmPW98ni90m4uQAJSWhpTg.png" /><figcaption>Link size with blue box. Highlighted in red <em>the gap</em>.</figcaption></figure><p>That gap might give us trouble, so the first thing is to remove it! It comes currently from the right panel:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kZqqD79JC5pRx9FX0gnFWw.png" /><figcaption>That padding-left is getting in the way</figcaption></figure><p>So now we only have to find it in the code and remove it:</p><pre>nav.bmenu article.panel {<br>  padding-left: 1.25rem;   /* Remove this */<br>}</pre><p>Of course if you remove it the panel will be too close to the &gt;, so let’s add some padding-right to those links to compensate:</p><pre>nav.bmenu a {<br>  padding-right: 1.25rem;<br>}</pre><p>See the arrow? We also have to move it to the left, since it’s an ::after element that is positioned absolutely:</p><pre>nav.bmenu &gt; a:not(.no-panel)::after {<br>  right: calc(0.5*0.5em);            /* before */<br>  right: calc(0.5*0.5em + 1.25rem);  /* after, add what we took out */<br>}</pre><p>It starts to look better; if we superimpose the &lt;a&gt; and the &lt;article.panel&gt;, we see they are border-to-border now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0NGxH0urFy6oXoD6tfuhcw.png" /></figure><p>With a small adjustment we can move the left bar where it belongs. A border-left: 1px solid #fff would have worked wonders here as well, or even a box-shadow. But let’s keep it close to the original:</p><pre>nav.bmenu article.panel::before {<br>  left: 1.25rem;  /* before */<br>  left: 0;        /* after */<br>}</pre><p>Voilà! Here it is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*svNQZPRIjq2JzrFzszQ0Jg.png" /></figure><h3>Fixing the Functionality</h3><p>The issue remains though. That was a red flag, but it turns out it wasn’t the issue since the right padding is within the panel.</p><p>The issue is that, if none of the links is hovered, the display: flex is not triggering. So let’s make the panels self-aware of their hover:</p><pre>/* Keep showing the panel when we log over it! */<br>nav.bmenu article.panel:hover {<br>  display: flex;<br>}</pre><p>And we also have to remove the selector for the first item, since this is giving some trouble with over-specificity. This will unfortunately hide the right panel while not hovering any specific link, but it’s a small price to pay for being able to use the menu. So just remove this whole block of code:</p><pre>/* Remove all of this: */<br>nav.bmenu &gt; a:not(:hover):not(:focus) ~ article.panel:nth-of-type(1),<br>nav.bmenu &gt; a.no-panel:hover ~ article.panel:nth-of-type(1) {<br>  display: flex;<br>}<br>nav.bmenu &gt; a:focus:not(:nth-of-type(1)):not(.no-panel) ~ article.panel:nth-of-type(1) {<br> display: none;<br>}<br>nav.bmenu &gt; a:hover:not(:nth-of-type(1)):not(.no-panel) ~ article.panel:nth-of-type(1) {<br> display: none;<br>}</pre><p>Now it definitely is fixed. I’d add a negative margin of -1px to the right panel because some browsers in some resolutions render partial pixels weirdly, but it’s good enough for now. Of course a <a href="https://github.com/dosyago-coder-0/mimic-bloomberg-menu-no-js/pull/2/files">PR is waiting</a> to fix the original one.</p><p><a href="https://francisco.io/demo/bloomberg/fixed/"><strong>Working Demo</strong></a> | <a href="https://francisco.io/demo/bloomberg/broken/"><strong>Broken Demo</strong></a></p><p>If you like this, follow me! More blog posts like this to come ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=652cf134d493" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Server.js 1.0 released — for Node.js 8 LTS]]></title>
            <link>https://medium.com/server-for-node-js/server-js-1-0-released-12a419ab187a?source=rss-fe52adf78e69------2</link>
            <guid isPermaLink="false">https://medium.com/p/12a419ab187a</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Francisco Presencia]]></dc:creator>
            <pubDate>Wed, 01 Nov 2017 13:16:09 GMT</pubDate>
            <atom:updated>2017-11-01T13:17:03.315Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<blockquote>I released <a href="https://serverjs.io/">the first official version of server.js</a>, a library to make developing a web server in Node.js a lot easier. Based on <a href="https://expressjs.com/">express</a>, <a href="https://socket.io/">socket.io</a>, <a href="https://helmetjs.github.io/">helmet</a> and more.</blockquote><p>One year ago I had a problem and I decided to solve it. I was teaching Node.js in a workshop with <a href="https://www.hackerparadise.org/">Hacker Paradise</a> and I got to the point where I normally say:</p><blockquote>This code is too complex to explain at this point, so let’s just copy/paste it and continue.</blockquote><p>That part was when adding all of the middleware to make Express have bodyparser, sessions, cookies, etc. I thought it’d be really nice to have this set of basic functionality working for everyone by default.</p><p>Now with server I’d do this and have a fully working website:</p><pre>const server = require(&#39;server&#39;);<br>const { get, post } = server.router;</pre><pre>server(<br>  get(ctx =&gt; &#39;Hello world&#39;),<br>  post(ctx =&gt; console.log(ctx.data))<br>);</pre><blockquote><a href="https://medium.com/server-for-node-js/getting-a-great-npm-name-b0b2b27a0e1b">Getting a great npm name</a></blockquote><h3>Modern javascript</h3><p>Another thing that I didn’t like about Node.js programming is <a href="http://callbackhell.com/">Callback Hell</a>. With Await/Async this is easily solved. Let’s say a simple scrapper that saves the links of the passed url into a database and replies to it:</p><pre>const server = require(&#39;server&#39;);<br>const { get, post } = server.router;<br>const { render, json } = server.reply;<br>const fetch = require(&#39;node-fetch&#39;);</pre><pre>// Up to you how to implement these (Cheerio + MongoDB?)<br>const scrapeLinks = require(&#39;./fetch-links&#39;);<br>const saveLinks = require(&#39;./save-links&#39;);</pre><pre>server(<br>  get(ctx =&gt; render(&#39;index.jade&#39;)),<br>  post(async ctx =&gt; {<br>    const saved = await Links.find({ url: ctx.data }).exec();<br>    if (saved.length) return json(saved);<br>    const body = await fetch(ctx.data).then(res =&gt; res.text());<br>    const links = scrapeLinks(body);<br>    await saveLinks(ctx.data.url, links);<br>    return json(links);<br>  })<br>);</pre><p>That’s the main logic for it. Quite intuitive and direct compared to the callback way. <a href="https://medium.com/server-for-node-js/async-await-are-awesome-c0834cc09ab">Async/await are truly awesome</a>.</p><h3>Achievements</h3><p>These are the things I am most proud of, from a personal point of view and for the project itself.</p><p>I could make <strong>the library that I enjoy</strong> and use for my personal projects. It is easy and intuitive. I found many bugs and edge cases from daily use and <a href="https://github.com/franciscop/server">would love that you report any bug</a> that you might find.</p><p>While neither of them officially released, it has great <strong>socket.io</strong> integration and a <strong>powerful plugin system</strong>. That is on top of being backwards-compatible with any <a href="https://serverjs.io/documentation/#express-middleware">Express middleware</a> that you can find, a big win IMO.</p><p><a href="https://serverjs.io/documentation/"><strong>The Documentation</strong></a> has seen a lot of care and hard work. I will do my best to separate it into a different module in the future to be able to redistribute it and use on other projects. <a href="https://documentation.agency/">Want some nice docs like those? Hire me</a>.</p><h3>Things I’d change</h3><p>Make it <strong>sooner</strong>! I didn’t expect it to take a full year. I knew it was a longer project, but I expected to release it 3–6 months ago. The two main reasons are life, which got in the way, and me trying to make it future-proof.</p><p>Get <strong>more people using it sooner</strong>. When I teach web programming to friends I still follow express route. However I know that if I am spending my time teaching friends and acquaintances they won’t care or they’d even be happy to give me a hand on this.</p><h3>Next steps</h3><p>First to take a small break. If it becomes popular it’s probably going to be short, but I’d like to explore some other areas for a bit.</p><p>Then, the main priority is expanding the documentation and tutorials. This is <strong>a lot</strong> of work but IMO one of the best return of investment for any library. If they cannot find it, it doesn’t exist kind of thing.</p><p>Finally, make a plan and look forward for the 1.1. This will include official socket.io and the full plugin system. Also, some pre-made plugins such as an auth one, sass, react, etc.</p><h3>Looking for Sponsors</h3><p>I’m also looking for sponsors for the project. It doesn’t get many visits but surprisingly it gets a <a href="https://npm-stat.com/charts.html?package=server">decent and steadily growing number of installs</a>. So this looks like a small but passionate userbase, feel free to sponsor the project: <a href="https://serverjs.io/sponsor/"><strong>Sponsor website</strong></a><strong>.</strong></p><h4>Please let me know what what you create:</h4><h3><a href="https://serverjs.io/">Server.js website</a>, <a href="https://serverjs.io/documentation/">Documentation</a> &amp; <a href="https://serverjs.io/tutorials/">Tutorials</a></h3><p>~happy hacking ♥</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12a419ab187a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/server-for-node-js/server-js-1-0-released-12a419ab187a">Server.js 1.0 released — for Node.js 8 LTS</a> was originally published in <a href="https://medium.com/server-for-node-js">Server for Node.js</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[About server.js]]></title>
            <link>https://medium.com/server-for-node-js/about-server-js-87e1df90a5c0?source=rss-fe52adf78e69------2</link>
            <guid isPermaLink="false">https://medium.com/p/87e1df90a5c0</guid>
            <category><![CDATA[motivation]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[about]]></category>
            <dc:creator><![CDATA[Francisco Presencia]]></dc:creator>
            <pubDate>Tue, 20 Jun 2017 18:14:36 GMT</pubDate>
            <atom:updated>2017-11-01T12:19:01.360Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<p>I have taught Node.js + express.js to quite some people and there’s always a point where I just have to say: “this part is way too complex to explain at this point, so just copy/paste this”. This breaking point is connecting express.js to all those middlewares.</p><p>When I was <a href="http://www.hackerparadise.org/">traveling with Hacker Paradise</a> through Asia and we got to the same point I decided to do something about it. First I created a <a href="https://github.com/franciscop/express-data-parser"><em>file upload middleware</em></a> and then started the ground work for what now is <em>server</em>.</p><p>The final trigger was <a href="https://medium.com/server-for-node-js/getting-a-great-npm-name-b0b2b27a0e1b">getting the package </a><a href="https://medium.com/server-for-node-js/getting-a-great-npm-name-b0b2b27a0e1b">server in npm</a>. After that and based on the previous experiments, I decided to set out for real and make something worthwhile. So I dug into express.js, middleware, routers, etc and now I&#39;m proud that <strong>server is something I use</strong> to make websites faster and easier.</p><p><a href="https://github.com/franciscop/server">Join me in Github</a> to get the best out of server and help Node.js achieve its full potential. Next up are websockets routes:</p><pre>const server = require(&#39;server&#39;);<br>const { get, socket } = server.router;<br>server(<br>  get(&#39;/&#39;, ctx =&gt; ctx.res.render(&#39;home&#39;)),<br>  socket(&#39;connect&#39;, ctx =&gt; ctx.io.emit(&#39;connected&#39;, ctx.socket.id)),<br>  socket(&#39;message&#39;, ctx =&gt; ctx.io.emit(&#39;message&#39;, ctx.data))<br>);</pre><h3>Goals</h3><p>These are the main things that I wasn’t happy with the state-of-the-art, so I decided to launch server to build upon the great work of express:</p><ol><li>Make things work by default (by domain):</li></ol><ul><li>Parsers: json, urlencoded, <strong>file uploads</strong>, etc.</li><li>Persistence: session, cookies, csrf, etc</li></ul><p>2. Make things simpler to use:</p><ul><li>Many low-level things work out of the box</li><li>Sensible, secure defaults =&gt; no need to change anything</li><li>Easily customizable options</li></ul><p>3. Make some important services available where possible, or some hooks to make it easier:</p><ul><li>Passport</li><li>Database (MongoDB, etc)</li><li>Websockets</li></ul><p>4. Better error handling (if possible). No more ALLCAPS error messages with no information at all.</p><p>This will in turn <strong>make it much easier to get started</strong>, for both people who are new to Node or for experienced people who don’t want to set-up everything again and again. The main frustration that I’ve seen from people coming from:</p><ul><li>Different web backgrounds (Ruby on Rails, PHP), where now they have to hunt down and compare dozens of libraries to do simple tasks.</li><li>Different programming backgrounds (Arduino, C++) where I have to explain not only how to get a server ready with these new tools, but also how the current state of the art and the fun of it is to build your own stack.</li><li>Starting from scratch. I pity those people starting with no programming experience coming to Node.js. This shouldn’t be so difficult, should it?</li></ul><p>So that’s it, those are the reasons for me to start server.js. <a href="https://github.com/franciscop/server">Star the package in Github</a> if you like it and check all the info in the <a href="https://serverjs.io/">official website</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87e1df90a5c0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/server-for-node-js/about-server-js-87e1df90a5c0">About server.js</a> was originally published in <a href="https://medium.com/server-for-node-js">Server for Node.js</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting a great npm name]]></title>
            <link>https://medium.com/server-for-node-js/getting-a-great-npm-name-b0b2b27a0e1b?source=rss-fe52adf78e69------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0b2b27a0e1b</guid>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[package-management]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Francisco Presencia]]></dc:creator>
            <pubDate>Tue, 20 Jun 2017 08:56:07 GMT</pubDate>
            <atom:updated>2017-06-20T08:56:07.578Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<p><em>Note: thanks to npm making this possible and for their awesome support.</em></p><p>You might be surprised to know that I am developing <a href="https://serverjs.io/">server.js</a> under the npm name “<em>server</em>”, so I can direct users to just do npm install server. Wait, wasn’t this package taken already?</p><p>In fact it was; there was a 0.0.3 version published a few years back. But npm’s “<a href="https://www.npmjs.com/policies/disputes">Package Name Disputes</a>” is pretty clear about it:</p><blockquote>“Some things are not allowed, and will be removed without discussion if they are brought to the attention of the npm registry admins, including but not limited to: […] “Squatting” on a package name that you <em>plan</em> to use, but aren’t actually using. […] Putting empty packages in the registry.”</blockquote><p>From the lack of use from the author and devs, npm decided to hand it over when the original author didn’t answer my emails. Let’s see how to do it.</p><h3>A package has a name</h3><p>First of all we have to identify a package name that we might want to use. My rule of thumb is to try to find a package that follows most of these:</p><ul><li><strong>Unstable</strong>: latest version in the low <strong>0.x</strong> or even in the <strong>0.0.x.</strong> This means the package is still marked as “in development” as per <a href="http://semver.org/">semver guideliness</a> so the work <em>should</em> still not be used in production by anyone.</li><li><strong>Inactive</strong>: The package has not received any significant update in years, meaning that the authors are probably long gone or don’t care anymore.</li><li><strong>Not used</strong>: The weekly installations are in the low numbers; they will never be 0 though, since there are many caches and crawlers just installing them (under 10/week is a good number). You don’t want to break packages used by thousands of developers.</li><li><strong>Trivial</strong>: there hasn’t been a lot of work put into the package. This is more of a respect thing as someone put a lot of work into it.</li></ul><p>I find this info with <a href="http://jerz.setonhill.edu/writing/e-text/url-hacking-do-it-yourself-navigation/">url hacking</a> writing <a href="https://www.npmjs.com/package/package">https://npmjs.com/package/NAME</a> for precise matching, but <a href="https://www.npmjs.com/search">the search functionality</a> has been improved greatly in the recent years so you can use that as well.</p><p>There was something weird going on in the early npm versions so the name is case-sensitive; you’ll have to check the <strong>lowercase </strong>name as that’s the only supported ones nowadays.</p><h3>Get the package</h3><p>Great! You found an amazing package name that follows most of the points mentioned above. The quoted dispute policy is to <em>automatically</em> remove a package, but we might also want to use a name that is not in direct violation of the conditions. It’s time to wear our peopleware hat.</p><p>It’s simple and <a href="https://www.npmjs.com/policies/disputes">well explained</a>: email the person holding the current package. Most people are actually easy to reason with so just ask nicely and give a valid reason (the name is perfect a package you are finishing). CC npm staff so in any way it will be resolved within 1–2 months.</p><p>The other person might not have access to that email or not care anymore, in which case npm will intervene and give their verdict about what will happen after few weeks.</p><h3>Next steps</h3><p>You might be asked by npm to publish from the 1.x version to avoid any possible compatibility issue. However you can get around this to not yet launch an official build by using 1.0.0-alpha.1 versions first.</p><p><a href="https://twitter.com/fpresencia">Let me know</a> if you get a great name or have any question! Also check out <a href="https://serverjs.io/">server.js</a> to make a full Node.js server easily with npm install server and:</p><pre>// index.js</pre><pre>// Include it and extract some methods for convenience<br>const server = require(&#39;server&#39;);<br>const { get, post } = server.router;<br><br>// Launch server with some options and a couple of routes<br>server({ port: 8080 },<br>  get(&#39;/&#39;, () =&gt; &#39;Hello world&#39;),<br>  post(&#39;/&#39;, ctx =&gt; console.log(ctx.data))<br>);</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0b2b27a0e1b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/server-for-node-js/getting-a-great-npm-name-b0b2b27a0e1b">Getting a great npm name</a> was originally published in <a href="https://medium.com/server-for-node-js">Server for Node.js</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use the Raspberry Pi!]]></title>
            <link>https://medium.com/@fpresencia/use-the-raspberry-pi-31d34867e219?source=rss-fe52adf78e69------2</link>
            <guid isPermaLink="false">https://medium.com/p/31d34867e219</guid>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[answers]]></category>
            <category><![CDATA[iot]]></category>
            <dc:creator><![CDATA[Francisco Presencia]]></dc:creator>
            <pubDate>Thu, 15 Jun 2017 23:03:56 GMT</pubDate>
            <atom:updated>2017-06-15T23:03:56.539Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the straw that breaks the camel’s back; as I’m learning and improving about how to use the Raspberry Pi I read this article called “<a href="http://www.makeuseof.com/tag/stop-using-raspberry-pi-everything/">Stop using a Raspberry Pi for everything</a>”.</p><p>But I tell you, use the Raspberry Pi! It sits in the middle ground from Arduino and a computer, so you can achieve most of both tasks. Want some easy I/O for motors or sensors? You got it. Want to do SSH or put a webcam and stream something to the internet? You also got it.</p><p>It is perfect for the DIY intersection between hardware and software. I would say it is the hardware equivalent to React, while Arduino would be more similar to jQuery.</p><p>However, I really think for programmers trying to get into hardware OR for hardware folks trying to get into software it makes a lot of sense.</p><p>Once you get started, you’ll get better and better over time. It is perfectly okay to use it even with projects where it might be overkill. In the same way that using React for a landing/static page is over the top, using the Raspberry Pi for blinking a LED is way too much.</p><p>HOWEVER, if you are a beginner or learning, do it! There’s not better way to get good at something than to practice at every chance you got, so making a blinking LED (Hello World) in the Raspberry Pi is totally worth it.</p><p>In the same way that you don’t <a href="http://microjs.com">browse this list</a> every time you want to make a website, it’d be silly to tell someone to start learning about NodeMCU, Arduino, ESP and many other devices every time they want to make some hardware.</p><p>At some point after you have learned enough you might want to switch to something more appropriate for your project, be it lower level or higher level. But saying not to use it is like saying to a beginner web programmer not to use jQuery or React. There is a place for everything, and using Raspberry to get started or a prototype ready is perfectly okay.</p><p>PS, many of the points in the article are valid, however you should start learning with one tool, stick to it and after you know your way around switch to the next one. Don’t try to learn N tools at the same time or you’ll get Hardware Fatigue (;</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31d34867e219" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Server.js beta 1 released]]></title>
            <link>https://medium.com/server-for-node-js/server-js-beta-1-released-d53d01468ac5?source=rss-fe52adf78e69------2</link>
            <guid isPermaLink="false">https://medium.com/p/d53d01468ac5</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es7]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[serverjs]]></category>
            <dc:creator><![CDATA[Francisco Presencia]]></dc:creator>
            <pubDate>Fri, 09 Jun 2017 14:44:38 GMT</pubDate>
            <atom:updated>2017-06-09T14:52:56.536Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<p>This release marks the end of a way longer than expected development cycle and the first public release for testing. <a href="https://github.com/franciscop/server/blob/master/api.js">The core functionality</a> for this version is released and will be kept compatible for the full 1.x cycle.</p><p>After 50 alpha releases — since NPM asked me not to publish 0.x versions — I am proud to release the first public-testing <strong>beta</strong> release. Feel free to <a href="https://serverjs.io/">install and use it</a> under the permissive MIT license:</p><pre>const server = require(&#39;server&#39;);<br>const { get, post } = server.router;</pre><pre>server(<br>  get(&#39;/&#39;, () =&gt; &#39;Hello 世界&#39;),<br>  get(&#39;/html&#39;, () =&gt; &#39;&lt;p&gt;I am a &lt;strong&gt;paragraph&lt;/strong&gt;!&lt;/p&gt;&#39;),<br>  post(&#39;/&#39;, ctx =&gt; console.log(ctx.data))<br>);</pre><h3>Test release</h3><p>The code is in a good state to be used right now and with your help I’ll be able to make it production-ready for the final 1.0.0. Right now it should work with Linux, macOS and Windows.</p><p>There are few things missing from the documentation so I do recommend everyone to use server.js only for small projects right now. But please do so, break it and <a href="https://github.com/franciscop/server/issues/">report it</a> so I can fix it!</p><p>If you have any questions about how to do something just open an issue and ask, it’ll also help building the documentation.</p><h3>Next steps</h3><p>Right <a href="https://serverjs.io/documentation/">now the documentation it’s just a stub</a> with some parts missing or inaccurate. The idea is for the documentation to be in a usable state for the Beta 2 so devs can effectively use it and then polish it all the way to the 1.0.0. Hopefully there will be just 2–3 betas.</p><p>It is a long road, but I think I will be able to launch the second beta with usable documentation in 2–4 weeks. For people using it now there’s <a href="https://github.com/franciscop/server/blob/master/api.js">a specification file</a> to make sure you know what the stable API is.</p><p>Finally and to make it truly production-ready many tests and examples must be added. I’ve been adding some — specially with unexpected bugs— but I’ll need to write many more.</p><h3>Try it out!</h3><pre>npm install server</pre><p>Then create a hello world in your index.js:</p><pre>const server = require(&#39;server&#39;);<br>server(ctx =&gt; {<br>  return &#39;Hello world!&#39;;<br>});</pre><p>Open http://localhost:3000/ and you’ll see it working. To know how to use it all see <a href="https://serverjs.io/">the official website</a>.</p><p>I would love to know what you think, so please <a href="https://news.ycombinator.com/item?id=14521776">leave your feedback on the Hacker News thread</a> and <a href="https://github.com/franciscop/server">check the code and star it on Github</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d53d01468ac5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/server-for-node-js/server-js-beta-1-released-d53d01468ac5">Server.js beta 1 released</a> was originally published in <a href="https://medium.com/server-for-node-js">Server for Node.js</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Please Mix Promises and Callbacks]]></title>
            <link>https://medium.com/@fpresencia/please-mix-promises-and-callbacks-b2d15da6166c?source=rss-fe52adf78e69------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2d15da6166c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Francisco Presencia]]></dc:creator>
            <pubDate>Fri, 07 Apr 2017 16:16:30 GMT</pubDate>
            <atom:updated>2017-04-29T01:53:40.341Z</atom:updated>
            <content:encoded><![CDATA[<p>I just read the article “<a href="https://spin.atomicobject.com/2017/04/06/nodejs-promises-callbacks">Never Mix Promises and Callbacks in NodeJS</a>” from the front-page of Hacker News and I found two errors that have nothing to say with what is explained in the article.</p><p>I <a href="https://medium.com/server-for-node-js/servers-middleware-promises-41d82a184452">do love promises</a> and think that <a href="https://medium.com/server-for-node-js/async-await-are-awesome-c0834cc09ab">async/await are awesome</a>, so I want to explain why it really fails. First let’s see the basics, you would not write this code for testing, as you know it will not work, right?</p><pre>it(&quot;should pass us a null if there are no users&quot;, function(done) {<br>  try {<br>    expect(&#39;a&#39;).to.equal(&#39;b&#39;);<br>    done();<br>  } catch (err) {<br>    // do nothing here<br>  }<br>});</pre><p>Here expect throws an Error when the expectation fails, so that example will never get to done() for that reason but won’t still be failed since it’s catched. The example in “<a href="https://spin.atomicobject.com/2017/04/06/nodejs-promises-callbacks/">Never mix Promises and callbacks in Node.js</a>” is basically that:</p><pre>// to start off, shouldn&#39;t callback be the first parameter?<br>function fetchFirstUser(iswhatIwant, callback) {<br>  knex.first().from(&quot;users&quot;).then((user) =&gt; {</pre><pre>    // If this throws an Error it is then catch()<br>    callback(user);</pre><pre>  // Let&#39;s ignore all our problems?:<br>  }).catch((e) =&gt; {<br>    callback(null);<br>  });  <br>}<br><br>it(&quot;should pass us a null if there are no users&quot;, function(done) {<br>  fetchFirstUser(function(user) {<br>    expect(user).to.be.null;<br>    done();<br>  })<br>});</pre><p>In either way callback() <em>should be</em> throwing exceptions as fetchFirstUser( ) expects a callback as the second parameter but it’s being passed as the first. This makes it to never be executed and thus timing out. Let’s assume though that it’s a typo/edition error, it will still not work right.</p><p><strong>You should not be catching the error you want to see for testing.</strong> In the same way that the first example in this article doesn’t make sense, when you use .catch() you are swallowing the errors that expect() throws.</p><p>So the code could be refactored to use the two parameters of then for example, which won’t catch what is thrown in the callback. Also using standard Node.js signature:</p><pre>function fetchFirstUser(callback) {<br>  knex.first().from(&quot;users&quot;).then((user) =&gt; {<br>    callback(null, user);<br>  }, callback);<br>  // you could add a .catch(console.log) to see why it fails<br>}<br><br>it(&quot;should pass us a null if there are no users&quot;, function(done) {<br>  fetchFirstUser(function(err, user) {<br>    expect(err).to.be.null;<br>    expect(user).to.be.null;<br>    done();<br>  });<br>});</pre><h4>Alternatives</h4><p>The first and most obvious one is to learn more about the inner workings of the testing framework you are using. Make some tests and find out why they work/don’t work. It took me a while to get used to it, but when I stopped fighting them and started really poking at them I learned a lot.</p><p>The second and not always possible is to switch to Async/Await (disclaimer: I love those). It is supported out of the box with Node.js 7.6 and with those you can simplify the code above to this:</p><pre>it(&quot;should pass us a null if there are no users&quot;, <strong>async</strong> () =&gt; {<br>  const user = <strong>await</strong> knex.first().from(&#39;users&#39;);<br>  expect(user).to.be.null;<br>});</pre><p>However if you are going to use ES7 please learn really well promises and async/await before doing so. <a href="https://ponyfoo.com/articles/understanding-javascript-async-await">This is a great resource for that</a>.</p><p><strong>Takeaways</strong>:</p><ul><li>Do not catch what you intend to throw</li><li>Use native async/await if possible</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2d15da6166c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Async/Await are awesome]]></title>
            <link>https://medium.com/server-for-node-js/async-await-are-awesome-c0834cc09ab?source=rss-fe52adf78e69------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0834cc09ab</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Francisco Presencia]]></dc:creator>
            <pubDate>Wed, 05 Apr 2017 19:41:00 GMT</pubDate>
            <atom:updated>2017-04-05T19:41:00.755Z</atom:updated>
            <content:encoded><![CDATA[<p>It <a href="https://twitter.com/FPresencia/status/844859374778535936">just became apparent to me</a> that <strong>an async function that is called returns a Promise </strong>and that is really great. The reason is that there are few libraries that work great with it, including <a href="https://serverjs.io/">server for Node.js</a> and Jest.</p><blockquote>Good news: <a href="http://stackoverflow.com/a/41757243/938236">from Node.js 7.6</a> you have native async/await support!</blockquote><h4>Server middleware</h4><p>By building <a href="https://comments.network/">Comments Network</a> I learned a couple of tricks. If we were to do it naively we could implement it like this with <a href="https://serverjs.io/">server</a>:</p><pre>// Promise-based requests<br>server(get(&#39;/story/:id&#39;, ctx =&gt; {<br>  request(`API CALL${ctx.req.params.id}`).<strong>then</strong>(api =&gt; {<br>    request(`HN${api.url}${ctx.req.params.id}`).<strong>then</strong>(hn =&gt; {<br>      // Do some work with `api` and `hn` here<br>      ctx.res.send(workedout);<br>    });<br>  });<br>}));</pre><pre>// Async/Await based requests<br>server(get(&#39;/story/:id&#39;, <strong>async</strong> ctx =&gt; {<br>  const api = <strong>await</strong> request(`API CALL${ctx.req.params.id}`);<br>  const hn = <strong>await</strong> request(`HN${api.url}${ctx.req.params.id}`);<br>  // Do some work with `api` and `hn` here<br>  ctx.res.send(workedout);<br>}));</pre><p>You can use it now and forget about messy Promises and Callback Hell. Of course you will have to use libraries that are based on Promises as well, since some of the popular Node.js libraries such as fs and request are callback-based (check out fs-promise and request-promises).</p><h4>Testing</h4><p>Now let’s see about Jest. By default, Jest and other testing frameworks accept two ways of doing asynchronous tests. Through a function that accepts a <em>done</em> parameter or through a function that returns a Promise. But thanks to <em>async </em>the third option is a no-brainer (<a href="https://github.com/franciscop/drive-db">see it live</a>):</p><pre>// Callback based<br>it(&#39;can be loaded&#39;, <strong>done </strong>=&gt; {<br>  drive.load().<strong>then</strong>(db =&gt; {<br>    expect(db.data).toEqual(jasmine.any(Array));<br>    expect(db.data.length).toBeGreaterThan(0);<br>    <strong>done</strong>();<br>  }).catch(<strong>done</strong>);<br>});</pre><pre>// Promise based<br>it(&#39;[promise] can be loaded&#39;, () =&gt; {<br>  <strong>return</strong> drive.load().<strong>then</strong>(db =&gt; {<br>    expect(db.data).toEqual(jasmine.any(Array));<br>    expect(db.data.length).toBeGreaterThan(0);<br>  });<br>});</pre><pre>// Async/Await based<br>it(&#39;[async] can be loaded&#39;, <strong>async</strong> () =&gt; {<br>  const db = <strong>await</strong> drive.load();<br>  expect(db.data).toEqual(jasmine.any(Array));<br>  expect(db.data.length).toBeGreaterThan(0);<br>});</pre><p>That’s it. You don’t even need a return as functions return when finished so they will resolve then as expected.</p><p><strong>HOWEVER</strong> not everything is as great as it looks. Testing for a case where an error is thrown is quite more difficult with <em>async</em>:</p><pre>// Callback based<br>it(&#39;can be loaded&#39;, <strong>done </strong>=&gt; {<br>  drive.load().catch(err =&gt; done());<br>});</pre><pre>// Promise based<br>it(&#39;[promise] can be loaded&#39;, () =&gt; {<br>  let passed = false;<br>  <strong>return</strong> drive.load().<strong>then</strong>(db =&gt; {<br>    passed = true;<br>  }).catch().then(() =&gt; {<br>    if (passed) throw new Error(&#39;Did not throw an error&#39;);<br>  });<br>});</pre><pre>// Async/Await based<br>it(&#39;[async] can be loaded&#39;, <strong>async</strong> () =&gt; {<br>  try {<br>    const db = <strong>await</strong> drive.load();<br>  } catch (err) {<br>    return;<br>  }<br>  throw new Error(&#39;Did not throw an error&#39;);<br>});</pre><p>But the good news is that with a bit of code you can fix this:</p><pre>throws = cb =&gt; async () =&gt; {<br>  try {<br>    const res = await cb();<br>  } catch(err) {<br>    return;<br>  }<br>  throw new Error(&#39;No error was thrown&#39;);<br>};</pre><p>Then you can use it like this with async/await; back to the good bits:</p><pre>it(&#39;[async] can be loaded&#39;, <strong>async</strong> () =&gt; {<br>  <strong>await</strong> throws(() =&gt; drive.load());<br>});</pre><p>The future for Javascript is looking quite good even though there’s a long, fragmented road to get there. I’m building <a href="https://serverjs.io/">server for Node.js</a> to get there faster, <a href="http://eepurl.com/cGRggH"><strong>subscribe</strong></a> or follow me to get updates!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0834cc09ab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/server-for-node-js/async-await-are-awesome-c0834cc09ab">Async/Await are awesome</a> was originally published in <a href="https://medium.com/server-for-node-js">Server for Node.js</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Server’s middleware ♥ Promises]]></title>
            <link>https://medium.com/server-for-node-js/servers-middleware-promises-41d82a184452?source=rss-fe52adf78e69------2</link>
            <guid isPermaLink="false">https://medium.com/p/41d82a184452</guid>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Francisco Presencia]]></dc:creator>
            <pubDate>Sat, 28 Jan 2017 21:34:05 GMT</pubDate>
            <atom:updated>2017-01-28T21:34:05.405Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<p>This is the journey of creating <a href="https://github.com/franciscop/server">a simple and powerful server for Node.js</a>.</p><p>I decided to step back and <a href="https://github.com/franciscop/server/issues/1">change the way middleware works</a> before committing to 1.0.0. It hasn’t been easy, however I think that we can achieve a lot more with ES6+ than with Connect’s middleware and Koa’s middleware is way too complex for Server’s purpose.</p><h3>Definition</h3><p>I decided to <a href="https://xkcd.com/927/">create a new standard</a> for Server’s middleware:</p><p><strong>Synchronous</strong>: just a function that gets the context and returns anything.</p><pre>// Parse the body from the request<br>const bodyParser = ctx =&gt; {<br>  ctx.req.body = parsebody(ctx.req);<br>};</pre><p><strong>Asynchronous</strong>: a function that gets the context and returns a promise that will be resolved (or rejected) when the processing finishes.</p><pre>// Using a Promise-aware library, more and more everyday<br>const auth = ctx =&gt; findUser(ctx.req.session.id).then(user =&gt; {<br>  ctx.req.user = user;<br>});</pre><pre>// Porting an existing callback-based library<br>const ported = ctx =&gt; new Promise((resolve, reject) =&gt; {<br>  doSomethingAsync({}, (err, cb) =&gt; {<br>    if (err) reject(err);<br>    resolve(cb);<br>  });<br>});</pre><p>This was a “what would the best way for creating middleware with ES6 from scratch?” kind of idea. I still needed to check if this makes sense at all.</p><h3>Joining middleware</h3><p>For testing I made a function that joins them. I got <a href="https://github.com/expressjs/express/issues/3148">bitten with express</a> when I tried to do the same (100% my fault for not learning how it worked better) but I was surprised at how easy it was when using promises.</p><p>The objective of <em>join</em> is that this code works as expected:</p><pre>// my-custom-middleware.js<br>const join = require(&#39;./join&#39;);</pre><pre>const parseBody = ctx =&gt; {<br>  ctx.req.body = bodyparser(ctx.req);<br>};</pre><pre>const auth = ctx =&gt; findUser(ctx.req.session.user).then(user =&gt; {<br>  ctx.req.user = user;<br>});</pre><pre>// Return a single middleware that chains them<br>module.exports = join(parseBody, auth);</pre><p>This join can be defined with just native code:</p><pre>// join.js<br>// Pass a group of middleware and return a single one<br>module.exports = (...mid) =&gt; ctx =&gt; mid.reduce((prev, next) =&gt; {</pre><pre>  // Pass always the original context; not the returned one<br>  return prev.then(next).then(fake =&gt; ctx);</pre><pre>// Get it started with the right context<br>}, Promise.resolve(ctx));</pre><blockquote><em>We should totally do </em><em>loadware(mid).reduce... with </em><a href="https://www.npmjs.com/package/loadware"><em>loadware</em></a><em> to flatten the array, but I didn&#39;t want to add this dependency for the example.</em></blockquote><p>That’s it. Now you get a single middleware from those two by just using native code and Promise-aware middleware.</p><h3>Compatibility with Express/Connect</h3><p>I also made a function to make any of the original express middleware work with server (making it promise-aware). It is quite easy to use:</p><pre>// compress.js<br>const compress = require(&#39;compression&#39;)<strong>({ /* opts */ })</strong>;<br>const modern = require(&#39;./modern&#39;);</pre><pre>module.exports = modern(compress);</pre><p>To allow for dynamic options is slightly more complex:</p><pre>// body-parser.js<br>const compress = require(&#39;compression&#39;);<br>const modern = require(&#39;./modern&#39;);</pre><pre>module.exports = ctx =&gt; {<br>  const middleware = compress(<strong>ctx.options</strong>.compress);<br>  return modern(middleware)<strong>(ctx)</strong>;<br>};</pre><h3>Problems</h3><p>The main problem is that a promise chain cannot be stopped in a non-error way so it’s not possible to easily halt the call even when a router has successfully been called.</p><p>We are <em>mostly</em> ignoring the return value and I think promises require to be resolved or rejected to avoid memory leaks, so leaving an unsolved promise also doesn’t help.</p><p>This leads to <strong>the first constrain</strong>:</p><p><strong>All the routers will be final; only the first router that matches a path will be used and the rest are ignored:</strong></p><pre>server(<br>  get(&#39;/&#39;, ctx =&gt; { /* called  */ }),<br>  get(&#39;/&#39;, ctx =&gt; { /* ignored */ }),<br>  get(&#39;/&#39;, ctx =&gt; { /* ignored */ }),<br>);</pre><p>The second but also important problem is handling errors. All of the middleware accepts a single parameter, <em>ctx</em>, so it cannot be analyzed to see which one is supposed to handle errors.</p><p>This leads to <strong>the second constrain</strong>:</p><p><strong>Only throw to the middleware chain when there is a truly catastrophic global issue; try to resolve the local issues within your middleware:</strong></p><pre>server(<br>  ctx =&gt; {<br>    // Recoverable error<br>    // NO: throw new Error(&#39;No nnn active. Halt it all!&#39;);<br>    // Yes:<br>    ctx.log(&#39;No nnn active. To use it make sure ...&#39;);<br>  },<br>);</pre><h3>Conclusion</h3><p>This is still alpha software, but so far every indication is that we can transition to an awesome Promise-aware world while easily bringing all of the ES5-world code. <a href="https://github.com/franciscop/server">See more about the project in Github</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41d82a184452" width="1" height="1" alt=""><hr><p><a href="https://medium.com/server-for-node-js/servers-middleware-promises-41d82a184452">Server’s middleware ♥ Promises</a> was originally published in <a href="https://medium.com/server-for-node-js">Server for Node.js</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>