<?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[Server for Node.js - Medium]]></title>
        <description><![CDATA[Journey to launching *server* for Node.js - Medium]]></description>
        <link>https://medium.com/server-for-node-js?source=rss----25f367e7b0---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Server for Node.js - Medium</title>
            <link>https://medium.com/server-for-node-js?source=rss----25f367e7b0---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 05 Jun 2026 19:46:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/server-for-node-js" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <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----25f367e7b0---4</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:10 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----25f367e7b0---4</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:37 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----25f367e7b0---4</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:08 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[Server.js beta 1 released]]></title>
            <link>https://medium.com/server-for-node-js/server-js-beta-1-released-d53d01468ac5?source=rss----25f367e7b0---4</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[Async/Await are awesome]]></title>
            <link>https://medium.com/server-for-node-js/async-await-are-awesome-c0834cc09ab?source=rss----25f367e7b0---4</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:01 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----25f367e7b0---4</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>