<?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 Alexandre Portela dos Santos on Medium]]></title>
        <description><![CDATA[Stories by Alexandre Portela dos Santos on Medium]]></description>
        <link>https://medium.com/@asantos00?source=rss-b7921bb85238------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tCSJOr5lFeGLfr_k2PVF4Q.jpeg</url>
            <title>Stories by Alexandre Portela dos Santos on Medium</title>
            <link>https://medium.com/@asantos00?source=rss-b7921bb85238------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 21:03:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@asantos00/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[I published a book — Deno Web Development ]]></title>
            <link>https://asantos00.medium.com/i-published-a-book-deno-web-development-e7c406d4886a?source=rss-b7921bb85238------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7c406d4886a</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[deno]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Alexandre Portela dos Santos]]></dc:creator>
            <pubDate>Thu, 01 Apr 2021 11:45:57 GMT</pubDate>
            <atom:updated>2021-04-01T11:45:57.502Z</atom:updated>
            <content:encoded><![CDATA[<h3>I published a book — Deno Web Development 🦕</h3><p>As some of you might know, I’ve been working on something for the last six months — a book!</p><p>Presenting <a href="https://www.amazon.com/gp/product/180020566X">Deno Web Development</a>, a book about <a href="https://deno.land/">Deno</a>, a secure runtime for JavaScript and TypeScript, and how to use it for web development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oTeHECFIPYc2XVII.png" /></figure><p>The book focuses on how you can write, test, maintain, and deploy JavaScript and TypeScript web applications using Deno.</p><h3>The approach</h3><p>It is a guided journey discovering this new runtime, understanding the reasons for its creation, what problems it solves, and how to use it to build a real-world application.</p><p>The book starts with “hello world” and finishes with an API deployed in a cloud environment. In the meantime, it covers topics such as dependency and configuration management, connecting with the database, structuring an application, testing, among many others.</p><h3>What to expect</h3><p>By the end of “Deno Web Development”, the reader will have all the knowledge to decide whether to use Deno in their next project.</p><p>As the book progresses, the reader will get to know the ups and downsides of the technology, not only because they’re listed there, but also because they’ll experience them as they build an application from scratch.</p><h3>The audience</h3><p>I tried to make the book approachable as an introduction to the technology but audacious enough to include many engineering best practices.</p><p>“Deno Web Development” targets people with JavaScript knowledge that want to know more about Deno, understanding how to use it to solve common industry challenges.</p><h3>Special thanks</h3><p>Publishing the book wouldn’t be possible without the opportunity offered to me by <a href="https://www.packtpub.com/">Packt</a></p><p>The same applies to my friends: Felipe, Gonçalo, Bruno, Nuno, János, João, and Miguel. Writing this book wouldn’t be possible without your help. Thank you for always being available to discuss a variety of topics and providing meaningful feedback. You’re the best! 🙏</p><p>And of course, my family and friends for how they encouraged me to follow this “adventure” of joining two of my passions: technology and writing, and writing a book.</p><h3>Where can I buy it?</h3><p>The book is now available globally, on <a href="https://www.amazon.com/gp/product/180020566X">Amazon</a> in Kindle and paperback versions.</p><p>I’d be happy to hear any feedback you have about it, so feel free to reach out to me if you have any questions about it.</p><p>If you’re curious, I’m thinking of writing a little more on how was the experience of writing the book in the following weeks, adding to what I already said on a previous <a href="https://authors.packtpub.com/interview-with-alexandre-portela-dos-santos/">interview</a>.</p><p>Thank you,</p><p><em>Originally published at </em><a href="https://alexandrempsantos.com/deno/i-published-a-book-deno-web-development/"><em>https://alexandrempsantos.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7c406d4886a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Our first hackathon: A behind the scenes story of how we did it]]></title>
            <link>https://asantos00.medium.com/very-cool-title-deb3ea55a2d8?source=rss-b7921bb85238------2</link>
            <guid isPermaLink="false">https://medium.com/p/deb3ea55a2d8</guid>
            <category><![CDATA[innovation]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[product]]></category>
            <category><![CDATA[people]]></category>
            <category><![CDATA[hackathons]]></category>
            <dc:creator><![CDATA[Alexandre Portela dos Santos]]></dc:creator>
            <pubDate>Wed, 31 Mar 2021 07:40:30 GMT</pubDate>
            <atom:updated>2021-03-31T09:56:05.546Z</atom:updated>
            <content:encoded><![CDATA[<p>At cloudmobility, we believe in enabling our customers to shape the future of mobility and transportation.</p><p>It’s from the first day that we believe that shaping the future of mobility is only possible with great people. That is why we strive to find the best, most creative, and highly engaged people. Those are all words we can use to define our current team.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zofdMZtIunu0q0UxyiNOzg.png" /></figure><p>Having such a creative team means that everyone has ideas on how to make our products better. The team’s voices, together with customer feedback have big importance on what features and products are part of cloudmobility.</p><p>We truly believe we have the potential to create innovative products. People have the opportunity to do it on a daily basis, while they work with their team. But we wanted even more. We wanted to create something that would stimulate people to think big, giving everyone the opportunity to build something they believe can move the needle on cloudmobility.</p><p>That’s what lead to the <strong>#1 cloudmobility hackathon</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iGN8TVKI2uXUB8t7LuTFnQ.png" /></figure><p>Besides how creative and innovative the people we have in-house are, cloudmobility has at its disposal a few more conditions that we consider ideal for an event such as a hackathon:</p><ul><li>We have deep knowledge of our own products and the market around them</li><li>We have a close connection with customers</li><li>We have privileged access to cloud resources</li><li>We know how cloudmobility works under the hood</li></ul><p>This together with the idea of having people with different teams interacting made it all even more appealing. What better way to share knowledge than having cross-functional teams working to develop an idea?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jfM9icz82VatSA18cSj0jg.png" /></figure><p>People would be motivated, get to know the colleagues better, have fun, and build something that would help cloudmobility? Not doing it would be a no-brainer.</p><p>Unfortunately, the global pandemic situation didn’t make it easy for us to get together and have fun, as we normally do. But since we’re a distributed team from such an early stage, doing the hackathon remotely wasn’t that big of a problem, I’ll tell you what we did to facilitate the hackathon further down this post.</p><p>To help scope the ideas, we had to define a focus for the hackathon. One that’s not too broad, but one that doesn’t limit people’s creativity.</p><h3>The focus</h3><p><em>Building products on top of cloudmobility namespaces (CNS)</em></p><p>We gave participants access to cloudmobility namespaces, and from there it’s up to them. The ideas could go from products that make use of cloud resources, to features that improve the platform and solve customer’s needs.</p><p>There was <strong>one single rule</strong>: all the projects/ideas need to run on the platform. Getting the people that are building a product to use it is a great source of feedback and an even better way to emphasize with customers, feeling the same challenges they do.</p><h3>The format</h3><p>The hackathon consisted of 1.5 days of building on an idea followed by a small 5-minute presentation with 2 minutes of a Q&amp;A section. Each team documented their project, as well as the problem it tries to solve and how they plan to do it.</p><p>This whole process was also documented on cloudmobility’s social networks during the day, so if you’re curious about how did it go, you can find it in our <a href="https://www.instagram.com/cloudmobility.io/">Instagram highlights</a> and on <a href="https://www.linkedin.com/company/cloudmobility">LinkedIn</a>.</p><h3>Ready, set, go!</h3><p>On top of the access to resources on cloudmobility’s platform, we created a hackathon starter kit, which included a few more things:</p><ul><li>Documentation of all the available APIs</li><li>Access to all the product code</li></ul><p>As a means to foster collaboration and discussion during the hackathon, each team had its video/audio room. These rooms were also open to everyone, resembling a physical hackathon environment. I can say it worked very well, as we’d feel the presence of everyone around us, and could quickly go and have a chat with them.</p><p>To help the participants, a dedicated team of advisors was available to help guide the teams and answer any questions arising during the hackathon, as well as provide technical help if needed.</p><p>From here, it was up to the participants, I can only say our hopes were high, and we weren’t wrong.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9XZOomMu-rSbPo6brCNFQg.png" /></figure><h3>Teams and ideas</h3><p>As we wanted people to be very motivated on whatever they were building, we let the teams form organically. We created a session where people — which we called idea CEOs — could pitch their ideas to find other people that were interested in developing them further.</p><p>This resulted in forming cross-functional teams of 2 to 4 people, working on the following ideas:</p><ul><li>S3 object storage — explore S3 object storage on cloudmobilty</li><li>Code focus — an easy way to bootstrap an application on cloudmobility, providing all necessary tools and configurations</li><li>Cloud shell — an in-browser shell to cloudmobility users</li><li>Terraform provider — a declarative way to provision cloudmobility resources</li><li>Quick preview — one-click deployments based on a git repo</li><li>Serverless compute — deploy serverless functions o cloudmobility</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n_iqhnNPPpEYd7p_5hgR1Q.png" /></figure><p>Just from hearing the quick pitches and seeing the enthusiasm of people around it, we were already excited. From here on, it only got better as the teams worked on this for one day and a half, and ended with a presentation that struck many “wows” on the audience.</p><p>All of the presentations clearly stated the problem they were trying to solve, and why. They looked at cloudmobility as a customer that wants to build something and presented a solution to the pain points experienced. On top of all of this, the teams also started thinking of what it would take to add such ideas to cloudmobility, which challenges we would have, and what was missing to make these features production-grade.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QJbNhUKc5GVdg39VWWW8fA.png" /></figure><p>If you’re as curious about these ideas as we were, we got the teams to tell us what they’re trying to solve, and to present their solution to you in a blog post such as this, so stay tuned!</p><h3>Conclusion</h3><p>The hackathon was even better than we expected. It was delightful to see the excitement in people, and even more interesting to see what can be done when you leave smart, creative people to build something out of their minds for a couple of days.</p><p>We’re thrilled with the hackathon results. We’re actively looking at the built projects and gathering the knowledge that resulted from them, to see how we can integrate them on the platform since they solve very concrete user problems.</p><p>The hackathon was a success in all aspects. It was definitely something that will not be a one-of-a-kind event! We’ll be posting more about these kinds of initiatives here, and we’ll fill our promise and share with you the individual team’s blog post about the projects.</p><p>At <a href="https://cloudmobility.io/"><strong>cloudmobility</strong></a>, we believe, that there are no limits for people who are ready to prove themselves and are driven by what they believe in.</p><p>Our work ethic is built around diversity and constantly challenging ourselves to deliver the best products for our customers. If you are curious, check out our <a href="https://cloudmobility.io/career#open-positions">open positions</a> and <strong>come join our team</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=deb3ea55a2d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adventures in deno land]]></title>
            <link>https://asantos00.medium.com/adventures-in-deno-land-19da0108972c?source=rss-b7921bb85238------2</link>
            <guid isPermaLink="false">https://medium.com/p/19da0108972c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[deno]]></category>
            <category><![CDATA[learning]]></category>
            <dc:creator><![CDATA[Alexandre Portela dos Santos]]></dc:creator>
            <pubDate>Tue, 13 Oct 2020 00:22:50 GMT</pubDate>
            <atom:updated>2020-10-13T00:22:50.170Z</atom:updated>
            <content:encoded><![CDATA[<p>Earlier this year, <a href="https://deno.land/">deno</a> was released.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*hV3aJKsyJp0dG5R0fWkktw.png" /></figure><p>As I was very excited ever since I first heard about it on <a href="https://youtu.be/M3BM9TB-8yA">Ryan Dahl’s talk</a> at <a href="https://jsconf.eu/">jsconf</a>, I had to give it a try.</p><p>This talk is one of my personal favorites, it is a lesson on humility. Having Ryan looking at what he built 10 years ago with a criticizing tone is interesting. Even when <em>node</em> is used by millions of people, its creator still feels bad about some decisions made at the time.</p><p>Getting back to what brought me here… After hearing of the launch of v1.0 I took some hours to learn more about it. The documentation is very well written and structured, which by following what they call <em>the manual</em> one could have a very good understanding of how to start using it.</p><h3>Building something</h3><p>After reading the documentation, it looked great, in theory. But my default way to learn is normally to <em>build something with it</em>. It normally helps me identify pains I’d have in the real world if I had to build a <em>real</em> application with it.</p><p>The decision was to <strong>build an API that connects to twitter</strong> and returns 15 tweets from a user with more than 5 likes, I called it <em>popular tweets</em>. This small server should then run on a Kubernetes environment.</p><p>If you wanna follow the code, <a href="https://github.com/asantos00/deno-twitter-popular">here you have it</a></p><p>At first, I was kinda lost and didn’t know any APIs. I’ve decided to go explore the <a href="https://deno.land/std">standard library</a>. I got very impressed by how approachable was the code, took some time to read it, and learned a ton.</p><p>It got this idea on the back of my mind, which might lead to a future article, similar to what <a href="https://twitter.com/paul_irish">Paul Irish</a> did 10 years ago on <a href="https://www.paulirish.com/2010/10-things-i-learned-from-the-jquery-source/">10 things I learned from the jquery source</a> but for deno source, might actually do it!</p><p>After getting to know the basics, installing the <a href="https://marketplace.visualstudio.com/items?itemName=justjavac.vscode-deno">VSCode plugin</a>, and deno, we were ready to start my adventure.</p><p>To be honest, <em>it wasn’t a real adventure</em>, everything looked so familiar that I almost forgot I was using a different runtime.</p><h3>Getting to code</h3><p>By using the standard library’s http server it was very easy to build a server and get it up running handling requests.</p><pre>import { serve } from &quot;./deps.ts&quot;;</pre><pre>const s = serve({ port: 8080 });</pre><pre>for await (const req of s) {<br>  req.respond({<br>    status: 200,<br>    body: &quot;Hello world&quot;,<br>  });<br>}</pre><p>Step 2 was to connect it to twitter API. Having fetch already included on deno made it very easy and familiar.</p><pre>fetch(<br>  &quot;https://api.twitter.com/1.1/search/tweets.json&amp;q=(from: ampsantos0 min_faves: 5)&quot;,<br>  { headers: new Headers([[&quot;content-type&quot;, &quot;application/json&quot;]]) }<br>)</pre><p>Deno opted for mimicking existing Web APIs where they existed, rather than inventing new proprietary ones. For APIs that are not web standard, the Deno namespace is used. This looks like a smart choice to me, improving discoverability and reusing knowledge developers already have of the existing APIs.</p><h3>Running it</h3><p>Running the code was a breeze. One of deno’s selling points is security and I couldn’t agree more, it improved over <em>node</em>. You notice it the first time you try to run a program:</p><pre>$ deno run ./index.ts</pre><p>Once we are, in this case, using network to both expose our <strong>endpoint</strong> (:8080) and access <strong>Twitter’s API</strong> without our explicit consent, here’s what you get:</p><pre>error: Uncaught PermissionDenied: network access to &quot;0.0.0.0:8080&quot;, run again with the --allow-net flag<br>    at unwrapResponse ($deno$/ops/dispatch_json.ts:43:11)<br>    at Object.sendSync ($deno$/ops/dispatch_json.ts:72:10)<br>    at Object.listen ($deno$/ops/net.ts:51:10)<br>    at listen ($deno$/net.ts:152:22)</pre><p>This is a very reasonable and comprehensive error, again, good job on this!</p><p>A good approach for this is by enabling whitelist permissions by using the flag --allow-net which deno does it in a very simple and pragmatic way:</p><pre>$ deno run --allow-net=0.0.0.0:8080,api.twitter.com index.ts</pre><p>When running the code, the --inspect flag enables developers to use Chrome Dev Tools the same way they did in <em>node</em>, the debugging experience is as good as developers are used to.</p><h3>Module resolution</h3><p>When Ryan first talked about deno, and the <em>mistakes made in node’s design</em>, one of the big things he mentioned that <em>node’s</em> way of importing modules was too complicated and had lots of edge cases.</p><p>Example:</p><pre>const path = require(&quot;path&quot;)</pre><p>The dependency we’re importing, <em>path</em> might come from <em>node</em> standard library. At the same time, it can come from <em>node-modules</em>, or you could have installed a dependency named <em>path</em>, right? Ok, now you found the dependency, do you know what is the file you are requiring? Is it index.js? What if <em>package.json</em> has a different <em>main</em> file defined?</p><p>Lots of unknowns…</p><p>What about local imports? When you do:</p><pre>const add1 = require(&quot;./utils/math&quot;)</pre><p>Is math a file? Or a folder with an index.js inside of it? What is the file extension? Is it <em>.js</em>, <em>.ts</em>?</p><p>You get the point… <strong>Node imports are hard</strong>.</p><p>Deno follows a golang like approach, of having <em>absolute urls</em>. If it sounds strange to you, bare with me. Let’s look at the advantages:</p><ul><li>It solves local imports by adding the extension to it.</li></ul><pre>import { add1 } from &quot;./utils/math.ts&quot;</pre><p>You know just from reading it that math.ts is a file.</p><ul><li>It solves third party imports by having an absolute URL</li></ul><pre>import { serve } from &quot;https://deno.land/std/http/server.ts&quot;</pre><p>No more magic module resolution.</p><p>This absolute module resolution enabled some fun stuff like what <a href="https://twitter.com/ralex1993/status/1261039838100221952">R. Alex Anderson</a> did, running code from a set of gists.</p><p><strong>Note</strong>: VSCode plugin functions well with the third party imports, you can cmd+click on dependency and you’re directed to the code, as usual.</p><h3>Keeping track of dependencies</h3><p>Let’s talk about managing dependencies. As <em>deno</em> simplified the module imports, it allowed it to <em>automatically cache</em> dependencies.</p><p>When you first try to run it, it downloads the dependencies, caches them, and then runs with the cached version.</p><p>To force the caching of a module without running it, you can run $ deno cache [module url].</p><p>You are probably thinking it is strange and error-prone to URLs all around the code? That’s right. You can manage it however you want, as all modules have absolute URLs now, it’s just code at the end of the day.</p><p>Deno recommends having a deps.ts file, you can call it whatever you want but since it <a href="https://deno.land/manual/linking_to_external_code#it-seems-unwieldy-to-import-urls-everywhere">is in the documentation</a>, I see this start becoming a standard. On that file, you can import all the dependencies from the URLs and export the methods used.</p><pre>// deps.ts<br>export { serve } from &quot;https://deno.land/std/http/server.ts&quot;<br>export { parseDate } from &quot;https://deno.land/std/datetime/mod.ts&quot;</pre><pre>// index.ts<br>import { serve } from &quot;./deps.ts&quot;</pre><p>Having one single deps.ts file allows you to do some caching (as you did in package.json) on docker builds.</p><pre>COPY deps.ts .<br>RUN deno cache deps.ts</pre><p>By doing this, the RUN command will only run if the deps.ts file changed. With this, and as the installation step is now <em>automatic</em>, running it on docker became simpler.</p><p>There is one thing that has to be taken care of with deno, we have to send the flags for the permissions.</p><pre>CMD [&quot;run&quot;, &quot;--allow-net&quot;, &quot;index.ts&quot;]</pre><h3>Deno binaries</h3><p>Deno provides an install command. But, as I said earlier, it does not install dependencies on the project, as that is done automatically.</p><p>Its usage is similar to the npm install --global flag, citing the explanation on the official website about install:</p><p><em>This command creates a thin, executable shell script which invokes deno using the specified CLI flags and main module. It is placed in the installation root’s bin directory.</em></p><p>When you install a global binary, you have to specify what permissions it will need to run, again, secure by default.</p><pre>$ deno install --allow-net --allow-read <a href="https://deno.land/std/http/file_server.ts">https://deno.land/std/http/file_server.ts</a></pre><p>And you can then run $ file_server</p><h3>Conclusion</h3><p>Coming from the JS/TS world I’d say deno got lots of things right. It has the familiarity of JS and TS with small twists, to the better side. Having the standard library written in TS is a big plus, at it isn’t always straightforward to set it up in <em>node</em>.</p><p>The standard library is great, it looks both readable and well thought. Quoting the deno_std main repo:</p><blockquote>deno_std is a loose port of Go’s standard library. When in doubt, simply port Go’s source code, documentation, and tests.</blockquote><p>This is funny and interesting at the same time, deno used the effort the golang community put in its standard lib to drive its own, the result looks great.</p><p>The permission system is great and intuitive. Module resolution is now simpler and removes pretty much all the magic we got used to in <em>node lands</em>. All the async APIs return Promises now. It means using await and .then everywhere, not incurring into callback hell and not needing tools like promisify and such.</p><p>Adding to all of this, deno also got inspiration from golang by shipping a lot of the essential tools in the main binary. Discussions about bundler, formatter, and test runner will no longer be a thing, and even if they are, there’s an official way now. I haven’t tried the test suite and the documentation generator yet, I might write about it later.</p><p>Gotta say the overall experience of building a (very small) application with it was very good and intuitive. Can’t wait to build something more <em>real</em> with it!</p><p>I’m excited to see how this will evolve and thus I wrote another article, my <a href="https://alexandrempsantos.com/second-adventure-in-deno-land/">second adventure in deno.land</a> where I go a little deeper on the runtime.</p><p><em>Originally published at </em><a href="https://alexandrempsantos.com/adventures-in-deno-land/"><em>https://alexandrempsantos.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19da0108972c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Second adventure in deno land]]></title>
            <link>https://asantos00.medium.com/second-adventure-in-deno-land-63011a8d59bc?source=rss-b7921bb85238------2</link>
            <guid isPermaLink="false">https://medium.com/p/63011a8d59bc</guid>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[deno]]></category>
            <dc:creator><![CDATA[Alexandre Portela dos Santos]]></dc:creator>
            <pubDate>Tue, 13 Oct 2020 00:19:43 GMT</pubDate>
            <atom:updated>2020-10-13T00:23:35.498Z</atom:updated>
            <content:encoded><![CDATA[<p>In my last post, I wrote about <a href="https://alexandrempsantos.com/adventures-in-deno-land/">my first adventure in deno.land</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*hV3aJKsyJp0dG5R0fWkktw.png" /></figure><p>It was a fun one, the excitement of trying some new technology was always there. <em>deno</em> left me thinking about new possibilities and asking myself what am I going to build with it.</p><p>Last time around, I built a small twitter bot in order to scratch the surface of the standard library and to get to know <em>deno</em> a little better in a deeper context than a simple “hello world”.</p><p>It was very well-received, way more than what I was expecting. It ended up being, at the time, my most read and reacted post ever. I guess I got quite lucky on the ”<em>deno</em> hype train”.</p><p>Back to what brought me here today. After exploring the standard library, module imports, simple permission system, and dependency management, today I’ll explore the following topics:</p><ul><li><a href="https://alexandrempsantos.com/second-adventure-in-deno-land/#lock-files">Lock files</a></li><li><a href="https://alexandrempsantos.com/second-adventure-in-deno-land/#official-vscode-extension">Official VSCode extension</a></li><li><a href="https://alexandrempsantos.com/second-adventure-in-deno-land/#documentation">Documentation generation</a></li><li><a href="https://alexandrempsantos.com/second-adventure-in-deno-land/#fine-grained-permissions">Permission system</a></li><li><a href="https://alexandrempsantos.com/second-adventure-in-deno-land/#running-code-in-the-browser">Running <em>deno</em> code in the browser</a></li><li><a href="https://alexandrempsantos.com/second-adventure-in-deno-land/#testing">Testing</a></li></ul><p>If you want to follow the code, <a href="https://github.com/asantos00/deno-twitter-popular">here you have it</a>.</p><h3>Lock files</h3><p>To complete the information from the last post about dependencies, I’ll write about lock files. They’re a standard practice in many languages in pretty much every production app. They’re used to describe an exact tree of dependencies, in order to make installations more repeatable, avoiding issues that may arise out of version misalignement.</p><p>In <em>deno</em> you can generate a lock file for the used dependencies by running</p><pre>deno cache --lock=lock.json --lock-write ./src/deps</pre><p>This command will <em>cache</em> (that local installs the used dependencies) based on a lock.json file. The --lock-write flag updates or creates the lock.json file. The last parameter is the file that uses the dependencies.</p><p>To install the dependencies while integrity checking every installed resource, one can run:</p><pre>$ deno cache -r --lock=lock.json deps.ts</pre><p>The <a href="https://github.com/asantos00/deno-twitter-popular/blob/master/lock.json">generated file</a> is nothing more than a json object of dependencies and its checksum</p><h3>Official VSCode extension</h3><p>The official vscode extension has been launched! However, it is the exact same that I have mentioned on my previous post. It simply got moved to the official repo, as the changelog states</p><blockquote>Moved from <a href="https://github.com/justjavac/vscode-deno">https://github.com/justjavac/vscode-deno</a> to <a href="https://github.com/denoland/vscode_deno">https://github.com/denoland/vscode_deno</a> in order to have an “official” Deno plugin.</blockquote><p>It works very well, autocompletes and files imports are fine, as expected.</p><h3>Documentation</h3><p>Another of the advantages presented by Ryan in his talk was that deno included a documentation generator on its toolchain. It doesn’t have (yet) a section on the website, but we’ll explore it a bit here.</p><h3>Browse modules documentation</h3><p>Even though deno has no install step, the cache lets you develop in an airplane (as you did with node_modules), as it loads the modules the first time and then uses the cached one.</p><p>While working on an airplane, what if you want to look at third party code docs? You can use your editor of choice, yes, but there’s an alterantive.</p><p><em>deno</em> provides a cool way to see the third party code documentation without having to browse the code.</p><pre>$ deno doc <a href="https://deno.land/std/http/server.ts">https://deno.land/std/http/server.ts</a></pre><p>This outputs the methods exposed by the standard library’s http server.</p><pre>function listenAndServe(addr: string | HTTPOptions, handler: (req: ServerRequest) =&gt; void): Promise&lt;void&gt;<br>  Start an HTTP server with given options and request handler</pre><pre>function listenAndServeTLS(options: HTTPSOptions, handler: (req: ServerRequest) =&gt; void): Promise&lt;void&gt;<br>  Start an HTTPS server with given options and request handler</pre><pre>function serve(addr: string | HTTPOptions): Server<br>  Create a HTTP server</pre><pre>function serveTLS(options: HTTPSOptions): Server<br>  Create an HTTPS server with given options</pre><pre>class Server implements AsyncIterable</pre><pre>class ServerRequest</pre><pre>interface Response<br>  Interface of HTTP server response. If body is a Reader, response would be chunked. If body is a string, it would be UTF-8 encoded by default.</pre><pre>type HTTPOptions<br>  Options for creating an HTTP server.</pre><pre>type HTTPSOptions<br>  Options for creating an HTTPS server.</pre><p>Very neat, right? A very nice way of having an overview of the modules exported symbols.</p><p>To see the documentation for a specific symbol, one can also run.</p><pre>$ deno doc https://deno.land/std/http/server.ts listenAndServe</pre><p>Which outputs</p><pre>function listenAndServe(addr: string | HTTPOptions, handler: (req: ServerRequest) =&gt; void): Promise&lt;void&gt;<br>    Start an HTTP server with given options and request handler<br>        const body = &quot;Hello World\n&quot;;     const options = { port: 8000 };     listenAndServe(options, (req) =&gt; {       req.respond({ body });     });<br>    @param options Server configuration @param handler Request handler</pre><p>You can use the documentation command to have an overview of your code’s exported modules, it works the same way.</p><pre>$ deno doc twitter/client.ts</pre><p>Output:</p><pre>const search<br>  Searches for the recent tweets of the provided username that have more than 5 likes</pre><pre>interface Tweet<br>  Fields in a tweet</pre><pre>interface TweetResponse<br>  The response from Twitter API</pre><p>The --json flag is also supported (however, not for symbols), and allows generating the documentation in the json format, enabling programmatic uses.</p><p>One great example of the documentation generation uses is <em>deno</em> <a href="https://doc.deno.land/https/github.com/denoland/deno/releases/latest/download/lib.deno.d.ts">runtime API</a>.</p><p>It uses Deno to generate modules with the --json command and provides a really nice layout around it. We just needed to add typedoc to our modules, like what we did <a href="https://github.com/asantos00/deno-twitter-popular/commit/dbac72b58f46ace067381cbdfc5708877b033aac#diff-8575744caf69ee401aa128c0f0d46a42R71">here</a>.</p><h3>Fine-grained permissions</h3><p>As we talked <a href="https://alexandrempsantos.com/adventures-in-deno-land/">in my previous post</a>, one thing that <em>deno</em> got very well was permissions. They’re easy to use and secure by default. Previously, I’ve explained that in order for a script to be able to access the network, for instance, you’d have to explicitly use --allow-net flag when running it.</p><p>That is true, however, I was alerted by my friend <a href="https://twitter.com/schmittfelipe">Felipe Schmitt</a> that in order for it to be stricter, we can use:</p><pre>deno run --allow-net=api.twitter.com,0.0.0.0 index.ts</pre><p>This will, as you probably guessed, allow network calls to api.twitter.com and from 0.0.0.0 but disallow all the other calls. Instead of allowing complete access to the network, we’re allowing just part of it, whitelisting and blocking everything else by default.</p><p>This is now very well explained on the <a href="https://deno.land/manual/getting_started/permissions">Permissions page</a>, which is one of the documentation improvements that were added after the v.1.0.0 launch.</p><h3>Running code in the browser</h3><p>Another very interesting feature of <em>deno</em>, is the bundle command.</p><p>It allows us to bundle your code into a single .js file. That file can be run as any other deno program, with deno run.</p><p>What I find interesting is that the generated code, when it doesn’t use the Deno namespace is that it <strong>can run on the browser</strong>.</p><p>The possibilities for this are limitless. For instance, what if I wanted my API to generate an HTTP client for frontends to interact with it?</p><p>We can write that client in <em>deno</em>, reusing API code (and types). Here’s the code to get the popular tweets.</p><pre>import { TweetResponse } from &quot;../twitter/client.ts&quot;</pre><pre>export function popular(handle: string): Promise&lt;TweetResponse&gt; {<br>  return fetch(`http://localhost:8080/popular/${handle}`)<br>    .then(res =&gt; res.json())<br>    .catch(console.error)<br>}</pre><p><a href="https://github.com/asantos00/deno-twitter-popular/blob/master/client/index.ts">Code</a></p><p>This code lives on the API codebase and it is written in <em>deno</em>. It uses the same types from the twitter client the API uses.</p><p>Having the API client living on the API codebase means that whoever updates the API can also update the client, abstracting the backend and API changes from the frontend code. This is not a <em>deno</em> feature but something that it enables via this bundling feature.</p><p>Then, we can run the bundle command and put the generated file in a folder.</p><pre>$ deno bundle client/index.ts public/client.js</pre><p>It will generate the client.js file that can run on the browser.</p><p>For demonstration purposes we can create a public/index.html file with the following code.</p><pre>&lt;script type=&quot;module&quot;&gt;<br>  // Imports the generated client<br>  import * as client from &quot;./client.js&quot;</pre><pre>  async function fetchTwitter(event) {<br>    // Uses the methods on it<br>    const result = await client.popular(event.target.value)</pre><pre>    /*<br>      Omitted for brevity<br>    */<br>  }<br>&lt;/script&gt;</pre><p><a href="https://github.com/asantos00/deno-twitter-popular/blob/master/public/index.html">Code</a></p><p>This code uses client that was initially written in <em>deno</em>, and is now a js file.</p><p>Now, this public folder can be served by any webserver. Since we’re talking about <em>deno</em>, we can take advantage of it and serve the files with standard library’s file server.</p><pre># inside the public folder<br>$ deno run --allow-net --allow-read <a href="https://deno.land/std/http/file_server.ts">https://deno.land/std/http/file_server.ts</a></pre><p>We can now visit http://0.0.0.0:4507/ and use our very archaic frontend to query for popular tweets. With this, our code can use the client that was <strong>originally written in deno</strong> on the frontend, to interact with the API.Documentation</p><h3>Testing</h3><p>Following <em>deno</em>’s goal of shipping the essentials in a single binary, testing is obviously included. The documentation is, again, quite good on this. With the help of the doc command, it gets very straight-forward to write tests.</p><pre>$ deno doc <a href="https://deno.land/std/testing/asserts.ts">https://deno.land/std/testing/asserts.ts</a></pre><p>This prints the documentation for the assert module from <em>deno</em> standard library</p><pre>function assert(expr: unknown, msg): &lt;UNIMPLEMENTED&gt;<br>  Make an assertion, if not `true`, then throw.</pre><pre>function assertEquals(actual: unknown, expected: unknown, msg?: string): void<br>  Make an assertion that `actual` and `expected` are equal, deeply. If not deeply equal, then throw.</pre><pre>function assertMatch(actual: string, expected: RegExp, msg?: string): void<br>  Make an assertion that `actual` match RegExp `expected`. If not then thrown</pre><pre>/* Cut for brevity */</pre><pre>function fail(msg?: string): void<br>  Forcefully throws a failed assertion</pre><p>Let’s write a simple test to our “isomorphic” client we created a few lines above.</p><p>Deno.test will be used to declare the test body, assertEquals will be called to make the assertion. In order to mock the server responses, we’ll spin up a server using standard-library <em>http</em>server_.</p><p>We expect that the popular method from the client calls /popular/:twitterHandle. Let’s create a test for that.</p><pre>import * as ApiClient from &quot;./index.ts&quot;<br>import { assertEquals } from &quot;../deps.ts&quot;<br>import { runServer } from &quot;../util.ts&quot;</pre><pre>Deno.test(&quot;calls the correct url&quot;, async () =&gt; {<br>  runServer(async req =&gt; {<br>    assertEquals(req.url, &quot;/popular/ampsantos0&quot;)<br>    await req.respond({ body: JSON.stringify({ statuses: [] }) })<br>  })</pre><pre>  await ApiClient.popular(&quot;ampsantos0&quot;)<br>})</pre><p><a href="https://github.com/asantos00/deno-twitter-popular/blob/master/client/index.test.ts">Code</a></p><p>Our runServer util is a very simple function that just spawns a web server that closes after the first connection.</p><pre>import { serve, ServerRequest } from &quot;./deps.ts&quot;</pre><pre>export const runServer = async (<br>  handler: (req: ServerRequest) =&gt; Promise&lt;any&gt;<br>) =&gt; {<br>  const server = serve(&quot;:8080&quot;)</pre><pre>  for await (const req of server) {<br>    await handler(req)<br>    server.close()<br>  }<br>}</pre><p><a href="https://github.com/asantos00/deno-twitter-popular/blob/master/util.ts">Code</a></p><p>We can now run the test. Remember that everytime we run a <em>deno</em> program we need to pass the permission flags.</p><p>It will run as test every file matching the following regex {*_,*.,}test.{js,ts,jsx,tsx}:.</p><p><strong>TLDR</strong>: It runs every file that has test in its name and ends with one of the mentioned file extensions.</p><pre>$ deno test --allow-net</pre><p>If the test is failing, we’re presented with a nice diff.</p><pre>test calls the correct url ... error: Uncaught AssertionError: Values are not equal:</pre><pre>    [Diff] Actual / Expected<br></pre><pre>-   &quot;/popular/ampsantos0&quot;<br>+   &quot;/popular/handle-that-doesnt-work&quot;</pre><pre>  throw new AssertionError(message);<br>        ^<br>    at assertEquals (https://deno.land/std/testing/asserts.ts:170:9)<br>    at file:///Users/alexandre/dev/personal/deno/testing-deno/client/index.test.ts:7:5<br>    at runServer (file:///Users/alexandre/dev/personal/deno/testing-deno/util.ts:9:11)</pre><p>In order to run just part of the tests, the --filter flag can be used.</p><pre>$ deno test --allow-net --filter=&quot;correct url&quot;</pre><p>And a path can also be sent as the last argument</p><pre>$ deno test --allow-net ./client</pre><p>You can follow all the listed changes related to tests on <a href="https://github.com/asantos00/deno-twitter-popular/commit/14b7a623ac84d689f9e9872685b93cd6bd138a9c">this commit</a>.</p><p>And with this, we have pretty much everything we need in order to write comprehensive tests. Again, the essentials are there, we can (and probably will) create a couple more test utilities composing on top of the standard library, but for simple tests like the one we just wrote, this is enough.</p><h3>Conclusion</h3><p>On our second adventure, we went a little further than just presenting the language.</p><p>We explored some other parts of the runtime. From testing, generating documentation, lock files, stricter permissions, to generating javascript code and running it on the client. All of them are features we considered useful when writing <em>production</em> code. We let benchmarks out for the next adventure 😉.</p><p>We can’t forget that we did all of this with the toolset that is <strong>included</strong> in <em>deno</em>, no libraries were used.</p><p>This doesn’t mean that developers will not use and write libraries. It means though that the standard library is very well written and easy to use. This opens the door for developers to write powerful, and meaningful abstractions on top of it.</p><p>Together with the standard library, the toolchain offered with the main binary proves itself very complete, aligned the goal of <em>Only ship a single executable</em>, mentioned on <em>deno</em> docs. I’d say all the essentials are there and you don’t have to worry about tooling.</p><p>This adventure took a little longer than expected. Thanks for reading it.</p><p>I hope it was as fun reading as it was for me to explore it. I’d love to hear what you have to say about it and answer all the questions you might have.</p><p><em>Originally published at </em><a href="https://alexandrempsantos.com/adventures-in-deno-land/"><em>https://alexandrempsantos.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63011a8d59bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using mocked APIs to increase developer productivity]]></title>
            <link>https://medium.com/ki-labs-engineering/using-mocked-apis-to-increase-developer-productivity-765cd68ef561?source=rss-b7921bb85238------2</link>
            <guid isPermaLink="false">https://medium.com/p/765cd68ef561</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[mock]]></category>
            <dc:creator><![CDATA[Alexandre Portela dos Santos]]></dc:creator>
            <pubDate>Wed, 22 May 2019 16:02:04 GMT</pubDate>
            <atom:updated>2019-05-22T16:04:33.838Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MBiqMFJ3rBIYFZ9FrPgtsw.jpeg" /></figure><p>When we’re developing a frontend, we just might be lucky enough to have a full-fledged API, although in the real world, for the most time, we’ll get ourselves into a position where we have to develop without an API is available with all the functionality we require in the future.</p><p>There are a few tools that enable us to minimize this dependency, I remember ember has the great ember-cli-mirage. It provides the functionality you need, deeply integrated with ember and makes you develop <strong>by default</strong> with a completely mocked API, which I think is a great principle to start with. <br>It is also great to be able to run the application without depending on external servers (imagine on a plane, on a trip without internet, or just on a computer with low memory).<br>You do not want your UI developers to run 3 servers just to develop a button.</p><h3>Usecase</h3><p>The last days we were faced with a similar issue. We’re developing a screen, we had the API signature, but the API was not ready yet.</p><p>One alternative would be to just have the payload somewhere hardcoded, while we were waiting for the finished API. <br>Sure, we can develop your button with that but then it is not possible to implement the part of the application that does the requests. We also wanted, in future, to spend as little effort as possible to change from the mocked data to a real API.</p><p>That solution did not look right, especially when we still remember ember-cli-mirage. Unfortunately, we can&#39;t use ember-cli-mirage with other libraries, even though we really miss the functionality it provides.</p><p>The solution we ended up with was a combination of json-server with route-parser and using axios request interceptors.</p><p>In our http-client we had calls to axios, so, the first thing we did was to add this line.</p><pre>// httpClient.js<br>import mockApiRequestInterceptor from &#39;./mockApiRequestInterceptor&#39;;</pre><pre>axios.interceptors.request.use(mockApiRequestInterceptor);<br>// Please keep in mind that if you use axios instance, <br>// you have to do it on the instance</pre><p>And we’ve created the request interceptor</p><pre>// mockApiRequestInterceptor.js<br>import UrlPattern from &#39;route-parser&#39;;<br>import { API_BASE_URL } from &#39;appConfig&#39;;</pre><pre>const MOCK_API_BASE_URL = &#39;http://localhost:3001/api&#39;;<br>const MOCK_URLS = [<br>  `${API_BASE_URL}/:user/posts/:id`<br>];</pre><pre>export default (config) =&gt; {<br>    if (!IS_DEVELOPMENT) {<br>        return config;<br>    }</pre><pre>    const matchedUrl = MOCK_URLS.find(mockUrl =&gt; {<br>        const pattern = new UrlPattern(mockUrl);<br>        return pattern.match(config.url);<br>    });</pre><pre>    if (matchedUrl) {<br>        config.url = config.url.replace(API_BASE_URL, MOCK_API_BASE_URL);<br>    }</pre><pre>    return config;<br>};</pre><p>The mocked URLs would be added to MOCK_URLS, and if there is a <em>mocked version of them</em> they will be redirected.</p><p>So, this code would redirect requests made from a URL that is https://mycrazyserver.com/api/asantos00/posts/123 to http://localhost:3001/api/asantos00/posts/123, and part of the problem was solved.</p><p>After this, we took advantage of another great package json-server(TLDR: <em>Serves JSON files through REST routes</em>).</p><p>We’ve created an npm script that runs this json-server with a few configurations (I will explain them later).</p><pre>// package.json<br>{<br>    &quot;scripts&quot;: {<br>        &quot;mock-api:serve&quot;: &quot;json-server --watch mock-api/db.json --port 3001 --routes mock-api/routes.json&quot;<br>    }<br>}</pre><p>And created a db.json file</p><pre>// mock-api/db.json<br>{<br>    &quot;posts&quot;: [<br>        {<br>            &quot;id&quot;: 1,<br>            &quot;title&quot;: &quot;Mocking an API with axios&quot;,<br>            &quot;author&quot;: &quot;asantos00&quot;,<br>            &quot;createdAt&quot;: 1557937282,<br>            &quot;body&quot;: &quot;Lorem ipsum dolor sit amet, consectetur.&quot;<br>        },<br>        {<br>            &quot;id&quot;: 2,<br>            &quot;title&quot;: &quot;Whatever post&quot;,<br>            &quot;author&quot;: &quot;asantos00&quot;,<br>            &quot;createdAt&quot;: 758851200,<br>            &quot;body&quot;: &quot;Lorem ipsum dolor sit amet, consectetur.&quot;<br>        }<br>    ]<br>}</pre><p>It automatically creates rest endpoints for every entity on the db.json file and watches the db file for changes.</p><p>As we said before, json-server creates REST endpoints for entities, this means that after we have the entity post on the db.json, the following endpoints are created:</p><ul><li>GET /posts - Returns the list of posts</li><li>GET /posts/:id - Returns post with the sent id</li><li>POST /posts - Creates a post</li><li>PUT /posts/:id - Replaces the post with the sent id</li></ul><p>The file to create custom routes is routes.json.</p><pre>// mock-api/routes.json<br>{<br>  &quot;/api/*&quot;: &quot;/$1&quot;,<br>  &quot;/:user/posts/:id&quot;: &quot;/posts?user=:user&quot;<br>}</pre><p>The routes file only says that whatever request comes to /:user/posts/:id, we redirect to the <em>automatically created</em> endpoint that is /posts. And yeah,json-server also supports filtering, we use the query param user to do it here.</p><p><strong>It’s done!</strong> Now, our app will continue making the requests to the endpoints that are implemented. But we can keep developing this page with the mocked API. <br>As soon as we want to use the real API, it is just a matter of removing the url from MOCK_URLS (which can also be extracted to a separate file) in mockApiRequestInterceptor file.</p><h3>Conclusion</h3><p>In the end, this solution really improves the process, helping us not being concerned about backend endpoints being done or not, while implementing all the cases in a <em>closer to real</em> environment. <br>Another nice thing about this is that it is also <strong>library agnostic</strong> as it only depends on the <em>http-client</em> so you can use it from react to backbone.js or even to react-native.</p><p>None of this would be possible without the <strong>amazing open source packages</strong>I’ve used, it was just a matter of getting the pieces together for the explained use case.</p><p>What solutions do you use to solve this problem? Is it something you stumble upon frequently?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=765cd68ef561" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ki-labs-engineering/using-mocked-apis-to-increase-developer-productivity-765cd68ef561">Using mocked APIs to increase developer productivity</a> was originally published in <a href="https://medium.com/ki-labs-engineering">KI labs Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying local state with reducers]]></title>
            <link>https://medium.com/ki-labs-engineering/simplifying-local-state-with-reducers-33ad9342b4f3?source=rss-b7921bb85238------2</link>
            <guid isPermaLink="false">https://medium.com/p/33ad9342b4f3</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[articles]]></category>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[reducer]]></category>
            <dc:creator><![CDATA[Alexandre Portela dos Santos]]></dc:creator>
            <pubDate>Wed, 27 Mar 2019 15:01:14 GMT</pubDate>
            <atom:updated>2019-03-27T15:01:14.494Z</atom:updated>
            <content:encoded><![CDATA[<p>Anybody that has been using react for some time is probably aware of the big amount of solutions to manage state. It always depends on multiple factors, project, context, team, size of an app…</p><p>A few months ago, my team at <a href="https://ki-labs.com/">KI labs</a> was given the responsibility to start migrating a jQuery + server-side rendered app to a single page app.<br>We first created a PoC, to decide which technology should we go with. At the time it was <a href="https://vuejs.org/">Vue</a> vs <a href="https://reactjs.org/">React</a>.</p><p>I’ll probably also blog for the reasons, motivations, and methods we use to experiment and choose technologies that best fit clients and projects at KI labs.</p><h3>Managing state</h3><p>The eternal discussion… <a href="http://redux.js.org/">Redux</a>? <a href="https://mobx.js.org/">Mobx</a>? <a href="https://reactjs.org/docs/context.html">Context</a>? People have preferences, but in the end, there are some solutions that are better suited to some projects.</p><p>By looking at the project needs, Redux seemed quite a bit of overhead. Even though it is a great library, global state was not a need. The same applies for Mobx. Regarding Context, we knew that we could end up using it in the future, probably not for state management, though.</p><p>Without the need to have global state, and with most of our state transitions being pretty simple, was there a need to add one more dependency to the project? Local state seemed enough…</p><h3>But we really liked how clean redux state transitions were…</h3><p>All redux benefits seemed cool: The functional paradigm, testing state transitions, having them documented (actions) and being able to mock states for testing.</p><p>We recalled the following Dan Abramov tweet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*tV54WK_p0G0MJUbayXafpQ.png" /></figure><p>In the end, we opted for a <em>hybrid</em> approach, having local reducers with local dispatches (pretty much what <em>useReducer</em> does, now that hooks were launched)</p><p><a href="https://reactjs.org/docs/hooks-reference.html#usereducer">useReducer</a> hook makes this pattern a little more common and easy to use. But we had a few class components that we wanted to manage state this way, and hooks weren’t live, yet.</p><p>We established one rule, setState could only be called in a single place inside a component, the dispatch method. And we actually built one small util for that, createDispatch.</p><p>Basically, we just had a util function called <em>createDispatch</em> that was used to define the dispatch inside a class (would probably work well as a decorator).</p><pre>const createDispatch = reducer =&gt; function(action) {<br>  this.setState(state =&gt; reducer(state, action));<br>} </pre><pre>class ProductList extends React.Component {<br>  dispatch = createDispatch(reducer)</pre><pre>  constructor(props) {<br>    super(props);<br>    <br>    this.state = reducer()<br>  }<br>}</pre><p>And now, all our state transitions just had to call this.dispatch(toggleSidebarVisibility()). We had reducer.js, as a file living along the component, as well as an actions.js file that defined all action types and action creators. (Example below)</p><pre>// reducer.js<br>const INITIAL_STATE = {<br>    topBar: {<br>        isVisible: true,    <br>    }<br>}</pre><pre>const reducer = (state = INITIAL_STATE, action = {}) =&gt; {<br>    switch(action.type) {<br>        case TOGGLE_SIDEBAR_VISIBILITY:<br>            return {<br>                ...state,<br>                topBar: {<br>                    ...state.topBar,<br>                    isVisible: !state.topBar.isVisible,<br>                }<br>            }<br>        default:<br>            return state<br>    }<br>}</pre><pre>// actions.js<br>const TOGGLE_SIDEBAR_VISIBILITY = &#39;TOGGLE_SIDEBAR_VISIBILITY&#39;;<br>const toggleSidebarVisibility = () =&gt; ({ type: TOGGLE_SIDEBAR_VISIBILITY });</pre><p>Reducer has its own tests, granting that all state transitions are tested and work, that being one of reducer pattern’s great advantages.</p><pre>// reducer.test.js<br>it(&#39;toggles sidebar visibility&#39;, () =&gt; {<br>    let state = reducer(undefined, toggleSidebarVisibility())<br>    expect(state.topBar.isVisible).toBeFalsy()<br>    <br>    state = reducer(state, toggleSidebarVisibility())<br>    expect(state.topBar.isVisible).toBeTruthy()<br>})</pre><h3>Best of both worlds</h3><p>By applying this hybrid solution we get to pick and choose the best of both worlds. Although now we have a solution that is a bit more verbose, we also have a very decoupled and testable state transitions, which seems like a pretty reasonable tradeoff.</p><p>Using the reducers pattern with local state in such a decoupled structure it enables an easy transition into redux (upon the need to support global shared state), as it’s a matter of lifting the needed state (literally copy &amp; paste) and everything else will still be working as expected.</p><p>What do you think of this approach? What do you normally use to manage state? Do you normally use setState? I would love to know.</p><p>At <a href="http://ki-labs.com/">KI labs</a> we’re very focused on using technology to help businesses solve problems, choosing the best tools for the job and making sure we’re helping companies and people thrive. We are faced with technical and business challenges on a daily basis, the same challenges we solve through creativity and innovation by our full-fledged team of people with different experiences, interests, and backgrounds.</p><p>Good news is that we are hiring top talent for our brand new office in Lisbon, if you want to work on a team with high standards and deliver top quality work on several projects, feel free to reach out!</p><p>Thank you for reading, please leave your feedback below.</p><p>Feel free to DM me at Twitter or just send me an email at <a href="/service/mailto:alexandre.santozz@gmail.com">alexandre.santozz@gmail.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33ad9342b4f3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ki-labs-engineering/simplifying-local-state-with-reducers-33ad9342b4f3">Simplifying local state with reducers</a> was originally published in <a href="https://medium.com/ki-labs-engineering">KI labs Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[(not) New year’s resolutions — 2017]]></title>
            <link>https://asantos00.medium.com/not-new-years-resolutions-2017-7219af17a3a0?source=rss-b7921bb85238------2</link>
            <guid isPermaLink="false">https://medium.com/p/7219af17a3a0</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[target]]></category>
            <category><![CDATA[self-awareness]]></category>
            <category><![CDATA[goals]]></category>
            <category><![CDATA[symfony-framework]]></category>
            <dc:creator><![CDATA[Alexandre Portela dos Santos]]></dc:creator>
            <pubDate>Wed, 11 Jan 2017 00:27:10 GMT</pubDate>
            <atom:updated>2017-01-11T16:43:07.095Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve read somewhere that the majority of people forget about their new year resolutions before January 15th.</p><p>This is not a new year’s resolution post since i’ve ended up establishing and started working on my goals since mid December 2016. Just to run away from the cliche of “new year resolutions”.</p><p>Spend 1 minute watching <a href="https://medium.com/u/c4ec9163657c">Gary Vaynerchuk</a> <a href="https://youtu.be/KT7dBk3BNPw">video</a> to understand what I’m talking about when it comes “resolutions”.</p><p>I’ve established 3 main areas for my goals, personal, profissional and financial.</p><h3>Personal</h3><ul><li>Become a calmer guy — I’m not a stressed person, but the calm I’m talking about is calm of thinking and reaction. I end up doing or saying some things without thinking and that’s something I want to stop happening. Also, if I become calmer my speaking skills (that are not bad) will improve too.</li><li>Stop drinking refrigerants — from a health standpoint, since my eating is not as good as it should, refrigerants are something I think I can easily stop drinking.</li><li>Improve my English skills — This actually started a few months ago when I joined <a href="http://uniplaces.com/">uniplaces.com</a> (worth checking out, especially if you are a student or landlord). Since the company has a lot of people from different parts of the world, the main language is English, and that’s obviously a must. This is also a pretty easy goal for me since I really love English.</li></ul><h3>Professional</h3><ul><li>Become a fluent back-end developer — most of my experience developing back end applications was in side projects. I never had to tackle a big code base or maintain a big back-end project until I joined Uniplaces so I don’t consider myself a fluent back-end developer, important goal!</li><li>Become comfortable doing Domain-driven design (DDD) — Here at Uniplaces we use DDD, that is something that really interests me, also, it’s a must for me so I can work with the apps we already have.</li><li>Become fluent using Symfony Framework — We use Symfony at Uniplaces too. As I want to become a fluent back-end developer and “learn” another language (other than JS), PHP was the choice.</li></ul><p>Just a small footnote — It is awesome when you’re in a company that is fully aligned with your objectives. My professional goals are all in sync with Uniplaces and that benefits both me and the company. A really big up for the company on this topic!</p><p>From my 3 months working there, couldn’t recommend more! If you’re ambitious and want to work with awesome people, Uniplaces is a (uni)place to really consider!</p><h3>Financial</h3><ul><li>Start putting in practice the advices from “Rich Dad, poor Dad”. Saving 10% and working in passive income. Also working on my financial IQ.</li></ul><p>I also want to document a little bit of my journey to complete those objectives along the year here on Medium, and this may count as an objective too.</p><p>Hope you liked it.</p><p>Tweet me at <a href="http://twitter.com/ampsantos0">twitter.com/ampsantos0</a> and tell me what you think about my first post!</p><p>Cheers,</p><p>Alexandre</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7219af17a3a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>