<?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 Pablo A. Del Valle H. on Medium]]></title>
        <description><![CDATA[Stories by Pablo A. Del Valle H. on Medium]]></description>
        <link>https://medium.com/@pablo.delvalle.cr?source=rss-3114c92aac3a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*e5AE0YorAMRa9BuQ</url>
            <title>Stories by Pablo A. Del Valle H. on Medium</title>
            <link>https://medium.com/@pablo.delvalle.cr?source=rss-3114c92aac3a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 10:41:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pablo.delvalle.cr/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[Next.js: 10 Tips and Tricks]]></title>
            <link>https://medium.com/@pablo.delvalle.cr/next-js-10-tips-and-tricks-56992837e9a7?source=rss-3114c92aac3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/56992837e9a7</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Pablo A. Del Valle H.]]></dc:creator>
            <pubDate>Thu, 17 Sep 2020 06:10:59 GMT</pubDate>
            <atom:updated>2020-09-17T06:10:59.042Z</atom:updated>
            <content:encoded><![CDATA[<h4>Check these not-so-secret tips and tricks that will optimize your development process when working with Next.js</h4><figure><img alt="Use these cool tips and tricks to step up your Next.js development" src="https://cdn-images-1.medium.com/max/1024/0*YDkZ1voip_TZ6wzs" /><figcaption>Photo by <a href="https://unsplash.com/@waguluz_?utm_source=medium&amp;utm_medium=referral">Andreas Wagner</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>With the <a href="https://nextjs.org/blog/next-9-5">latest release of <strong>Next.js</strong></a>, a bundle of new features were put out in the wild for developers to take advantage. Most of these new items will greatly increase your <strong>team’s productivity</strong>, your <strong>application performance</strong>, as well as your ability to <strong>measure your code’s overall speed and points to optimize</strong>.</p><p>Let’s review a few of these features while, at the same time, let’s throw in a few others items that were released in previous versions which can greatly improve your <strong>Next.js</strong> development experience.</p><p><strong>1. Next.js will automatically bootstrap TypeScript config files during the first run</strong>. One of the tedious tasks you run into when starting a new <strong>TypeScript</strong> project relates to correctly setting up the configuration for your <strong>TypeScript</strong> interpreter. <strong>Next.js</strong> will do this for you. It will automatically detect that your project is a <strong>TypeScript</strong> project and will create a default tsconfig.json file. It will also throw a next-env.d.ts file, which will be used by the <strong>TypeScript</strong> compiler.</p><figure><img alt="Next.js will generate a tsconfig.json file for you automatically." src="https://cdn-images-1.medium.com/max/1024/1*q9Dks2gzRsM4lFRGo9T50w.png" /><figcaption>When you run your <strong>Next.js</strong>/<strong>TypeScript</strong> project for the first time, it will detect that this is a <strong>TypeScript</strong> project and will automatically create a tsconfig.json file with default values.</figcaption></figure><p>After running this, if you list the files in your root directory you’ll notice two files were automatically created: tsconfig.json and next-env.d.ts.</p><p><strong>2. Understand the difference between a ‘browser log’ and a ‘terminal log’</strong>. Let’s face it, console.log is a precious, albeit rudimentary, tool on every Front-End developer’s belt. Major browsers, such as Chrome, Firefox or Safari, allow us to interact with the application through the console messages at run time, which will double as a sort of live-debugging device.</p><p>Generally, whenever you enter a console.log you expect to check out its output in the browser’s console, however since we have frameworks such as <strong>Next.js</strong>, we can run code before the rendering of the page, this means that the DOM object is not even started, thus some console.logs will be send directly to the terminal that is running your <strong>Next.js</strong> app.</p><p>An example of this can be seen in console.logs in getStaticProps method or in your pages/_app.js script.</p><p>Consider the following component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0fb4e2988ec0aaaa1e58df22afb279e4/href">https://medium.com/media/0fb4e2988ec0aaaa1e58df22afb279e4/href</a></iframe><p>Notice that when you run this project, you’ll see this in the console running the the Next app:</p><figure><img alt="Terminal’s output." src="https://cdn-images-1.medium.com/max/1024/1*tpBuFWR84nEwJk4THHXBvA.png" /><figcaption>The console log will output both strings in the terminal.</figcaption></figure><p>Both strings “<em>in getStaticProps…</em>” and “<em>in the component…</em>” will be sent to the terminal.</p><p>If you check the browser’s console, this is the output:</p><figure><img alt="Browser’s output." src="https://cdn-images-1.medium.com/max/1024/1*oqwL_Eh_QK48EREIxlQXUg.png" /><figcaption>Browser’s output of the console log.</figcaption></figure><p>In this case, you will only get the “<em>in the component…</em>” output. The takeaway is that both build-time and run-time console.logs will be sent to the terminal, while only run-time console.logs are sent to the browser’s console.</p><p><strong>3. Next.js understands if your application source code lives in the root of your project or inside a /src directory</strong>. Traditionally, Front-End projects tend to use the /src directory at the root of your project to keep all your source files. <strong>Next.js</strong> will check this directory by default, however it can also work fine if you skip this directory altogether.</p><p>For example, if you have your index page file in /pages/index.tsx it will work just the same if your index resides in <strong>/src/</strong>pages/index.tsx.</p><figure><img alt="A page that can be rendered as static will display a lightning icon at the bottom right corner of it." src="https://cdn-images-1.medium.com/max/822/1*L-BhY25tyJHRGAJf6nSxUA.png" /><figcaption>When you see the lightning icon, it means that this page can be optimized as completely static.</figcaption></figure><p><strong>4. The little lightning icon shows if your page is pre-rendered</strong>. When running your application in development mode you can instantly identify if your page does not have any dependencies and it can be built completely at build time, which in turns renders a static page that will be extremely fast.</p><p>If you were to add, say the getStaticProps async method, your page will depend on whatever props this method returns, thus invalidating the static rendering –you will not see the lightning icon in your page–.</p><p><strong>5. You can use integrated Web Vitals analysis</strong>. This one we discussed in a <a href="https://medium.com/swlh/new-features-introduced-in-next-js-9-4-and-real-world-applications-53d6b8f81570">previous article</a>, but is well worth mentioning again. <a href="https://web.dev/vitals/">Core Web Vitals</a>, released by Google, and built on top of Lighthouse, the famous web analyzer in Chrome, now exists within <strong>Next.js</strong> to give you metrics to evaluate the performance of your website.</p><p>From <a href="https://nextjs.org/blog/next-9-4#integrated-web-vitals-reporting"><strong>Next.js</strong> release notes</a>:</p><blockquote>In order to aid reporting Core Web Vitals to your analytics service we have introduced, <a href="https://www.techrepublic.com/article/insiders-look-at-googles-web-framework-contributions-to-next-js-and-more/">in collaboration with Google</a>, a new method called reportWebVitals which can be exported from pages/_app.js</blockquote><p>So, assume the following _app.js:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/111af24716231fc535c5840b959f00ed/href">https://medium.com/media/111af24716231fc535c5840b959f00ed/href</a></iframe><p>This will generate in the console of the browser the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h0h6RIXx3OxKp8GO-ZgClQ.png" /><figcaption>`reportWebVitals`output.</figcaption></figure><p><strong>6. You can avoid complex import paths using the built-in dynamic path composer</strong>. This one also was mentioned in a previous article, but it will really add up to your development experience, so it is great to mention it again (especially when used in conjunction with the next tip).</p><p>The <strong>dreaded “spaghetti import” disaster </strong>is a concern addressed in the last release of <strong>Next.js</strong>.</p><p>You can combine two highly requested features in your jsconfig.json or, for <strong>TypeScript</strong> projects tsconfig.json to this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/016ff7d198d200a746b6991cb8a6d5ad/href">https://medium.com/media/016ff7d198d200a746b6991cb8a6d5ad/href</a></iframe><p>What is happening here?</p><p>`<strong>baseUrl</strong>` will point to the root of your imports, if you want it to be the root of your project, then it should be a dot “.”, however, it can be customized to any directory within your structure.</p><p>`<strong>paths</strong>` will allow you to alias any directory in your project with a string. This enables you to <strong>import files with shorter, more descriptive names</strong>.</p><p><strong>7. Rewrites, Redirects, and Headers</strong>. This feature was released in the latest 9.5 release. It allows the app to manipulate the user’s request with redirects and rewrites, plus sending custom headers to the client. All these new features can be set within the next.config.js file.</p><p><strong>Rewrites</strong>: so let’s take <strong>Next.js</strong> documentation example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f55602367bcc90c3df444a3f0683fdae/href">https://medium.com/media/f55602367bcc90c3df444a3f0683fdae/href</a></iframe><p>Which, evidently, redirects all paths under /backend/ to example.com (carrying over the original path).</p><p>Since the rewrites method returns an array you can have several rewrite rules. If you read the <a href="https://nextjs.org/docs/api-reference/next.config.js/rewrites">rewrites documentation</a> you will find that you can use several variables and even regular expressions.</p><p><strong>Redirects</strong>: before release 9.5, setting up a redirect in your <strong>Next.js</strong> application required some extreme coding gymnastics with the _error script or setting up a server just for the redirection.</p><p>Now you can just export the async method redirects in your next.config.js script:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/396beeb8fcee6759de613b0915eca9b2/href">https://medium.com/media/396beeb8fcee6759de613b0915eca9b2/href</a></iframe><p><strong>Headers</strong>: and finally, you can now send custom headers with the async method headers. By using the same keywords, you can send custom headers for any paths matching the source key.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/570af35883a3ca7acc47cfcadaf07d8f/href">https://medium.com/media/570af35883a3ca7acc47cfcadaf07d8f/href</a></iframe><p><strong>8. Trailing slashes not returning 404</strong>. Originally, on <strong>Next.js</strong> all paths ending with a trailing slash would return a 404 error page. By adding the trailingSlash property to the next.config.js exports you can control how to handle the trailing slash within your app.</p><p>Options for this property are:</p><ul><li>true: will force a redirect to all non-slash-ending paths to ending-slash path.</li><li>false: default behavior, trailing slash will be treated as a different path and will return 404 error page.</li></ul><p>The setup for this setting will affect the next/link behavior as well.</p><p><strong>9. Next.js deployments</strong>. While there are multiple ways to deploy <strong>Next.js</strong> projects, a very fast way is to use Vercel’s infrastructure. Vercel is actually the owner and developer of <strong>Next.js</strong>, which will give you some confidence in their architecture.</p><p>There is a full-fledged <a href="https://nextjs.org/docs/deployment">page detailing the process here</a>.</p><p><strong>10. Dynamic catch-all routes</strong>. Using the syntax [[...slug]] you can create dynamic catch-all routes. For example, you can create a file /src/pages/posts/[[...slug]].js file. Now, this script will catch the /post path, but it will also catch /posts/new, or /posts/delete/2.</p><p>The slug will be sent as a prop to the page component as an array made up by the parts of the path. For example, our previous url /posts/delete/2 will produce the prop {slug: [&#39;delete&#39;, &#39;2&#39;]}.</p><h3>What’s Next and Further Reading</h3><p>Learn more about performance and speeding up your website:</p><ul><li><a href="https://medium.com/swlh/implementing-a-simple-redis-cache-with-next-js-5103976de188">Implementing a Simple Redis Cache With Next.js</a></li><li><a href="https://medium.com/@pablo.delvalle.cr/an-opinionated-basic-next-js-files-and-directories-structure-88fefa2aa759">An opinionated basic Next.JS files and directories structure</a></li><li><a href="https://medium.com/swlh/dockerize-your-next-js-application-91ade32baa6">Dockerize your Next.JS application</a></li><li><a href="https://medium.com/swlh/fetching-and-hydrating-a-next-js-app-using-getserversideprops-and-getstaticprops-65bfe42afed8">Fetching and hydrating a Next.JS app using `getServerSideProps` and `getStaticProps`</a></li></ul><p>Further reading:</p><ul><li><a href="https://nextjs.org/docs">Official Next.js ‘Getting Started’ page</a></li><li><a href="https://nextjs.org/blog/next-9-5">Next.js 9.5 Release notes page</a></li></ul><h3>Thanks for reading!</h3><p>Find me on <a href="https://www.linkedin.com/in/pablo-del-valle">LinkedIn</a>, <a href="https://medium.com/@pablo.delvalle.cr">Medium</a>, <a href="https://github.com/delvalle">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56992837e9a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing a Simple Redis Cache With Next.js]]></title>
            <link>https://medium.com/swlh/implementing-a-simple-redis-cache-with-next-js-5103976de188?source=rss-3114c92aac3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5103976de188</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Pablo A. Del Valle H.]]></dc:creator>
            <pubDate>Thu, 27 Aug 2020 07:24:49 GMT</pubDate>
            <atom:updated>2020-08-27T18:50:27.265Z</atom:updated>
            <content:encoded><![CDATA[<h4>Create a simple Next.js App that connects to HealthCare.gov API optimizing the experience with Redis Cache</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zoVh3_ZEtoqh765t" /><figcaption>Photo by <a href="https://unsplash.com/@nexgenfx?utm_source=medium&amp;utm_medium=referral">Luca Campioni</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>For most websites, the changing pieces don’t actually vary that often. That immutability makes them first-rate candidates to be cached to avoid the roundtrip to fetch the content from either a database, web service or third party end-points.</p><p>Consider a blog article that you wrote. It will be rather unlikely that this article will change over time more than once or twice, for instance, to adjust outdated information or to add a correction suggested by a reader. However, in a regular scenario, every time a visitor hits that blog page, your database will also get a hit. If your page gets 100,000 visitors, then you will get that many database-reads. And, granted, reads are generally cheap, however, in a scenario of high-performance, high-availability, each millisecond counts.</p><p>Furthermore, if your data comes from a third-party solution –say a remote web service– then each roundtrip to access the information you require will add up, in terms of network bandwidth, how many concurrent connections your remote server can handle, or even just dealing with an error on a system that you can’t debug or fix quickly.</p><p>Having an in-memory cache database can definitely help in optimization, unexpected datastores behaviors, consistency, and even save you a few bucks.</p><h4>Pitfalls to keep in mind before implementing an in-memory cache</h4><p>At this point, I must make the caveat that there are a few pitfalls that you need to be aware of before going full throttle with Redis, Memcache or any other in-memory database alternative. Please review the following list of potential pitfalls:</p><h3></h3><p>There are two hard things in computer science: cache invalidation, naming things, and off-by-one errors.</p><ul><li><strong>Cache invalidation is, still today, one of most challenging tasks there is in computer engineering</strong>. The other two, according to <a href="https://twitter.com/codinghorror">Jeff Atwood</a> from CodingHorror and founder of StackOverflow.com are naming things and off-by-one errors. Really, it can potentially make you lose hours on a wild goose chase. For this, I recommend having a strong game plan (cache coherence protocol), a cache expiration strategy, avoid bloating your cache with unnecessary data (such as volatile information), and finally having a periodic cache validator tuned in such a way that makes sense for your product and traffic.</li><li><strong>Be on the lookout for extra-greedy caching</strong>. This one is somewhat related to the previous and the next item. In essence, you want to be 100% in control of what chunks you are caching and for how long you will be storing said cache. A sporting event that happened last week will have the same score forever, it will not change. So you can, with confidence, store it and cache it. However if the game is live and happening right now you need to be able to update the score often, unobtrusively, probably not caching at all.</li><li><strong>Not every project is a good candidate for caching</strong>. Ideally, you want to be very careful and strategic on what sections of your site you will be caching. It makes total sense to cache an article, while it would be a really bad idea to cache a comments section, private user information such as passwords or credit cards. As mentioned above, cache invalidation is hard as it is, and you do not want to go down the rabbit hole trying to figure out why your page is not refreshing properly.</li><li><strong>Avoid storing complex structures</strong>. While Redis is more than capable of storing <a href="https://redis.io/topics/data-types-intro">Lists, Set, Hashes, and even Streams (among others)</a>, you may want to adhere to the <a href="https://en.wikipedia.org/wiki/KISS_principle">KISS principle</a>. As you introduce more intricacy within your data structures you will end up defeating the purpose of having a super fast off-the-shelve data from an in-memory database. Keeping it at key-value construction will generally pay off for what we want.</li><li><strong>Maintenance</strong>. This one is true to practically every software you install and let live in the wild of the public Internet. You are going to need someone with a fair level of expertise on how to implement and maintain your system. Nevertheless, I should also mention that Redis is very well documented and creating a single node in-memory cache database is generally straight forward.</li></ul><p>Having said the above, let’s try and create a very simple Next.js application that connects to HealthCare.gov open API.</p><h4>Step 1: Creating a simple Next.js Application</h4><p>Using Next.js as our engine to connect to an API is quite a wise decision, since we can take advantage of its server-side rendering to fetch the results to serve a fully hydrated page.</p><p>Let’s start with an empty standard project:</p><pre>npm init -y</pre><p>Next, we’ll get Next.js and React dependencies:</p><pre>npm i -S next react react-dom</pre><p>If your project runs with Typescript, install all the necessary libraries and types here as well. For the sake of simplicity we’ll make it non-Typescript, however the example could be transformed easily.</p><p>For the bare minimum Next.js project to run we need an index page. Create an index.jsx file under src/pages/index.jsx.</p><p>For starters, let’s drop this code in this index file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e8e2171a03ebd143da01b9a3bfd2b4e/href">https://medium.com/media/1e8e2171a03ebd143da01b9a3bfd2b4e/href</a></iframe><p>Then to keep track of how your page is going you’ll need to add a script to call next dev from your package.json, like this:</p><pre>...<br>  &quot;scripts&quot;: {<br>    <strong>&quot;dev&quot;: &quot;next dev&quot;</strong><br>  },<br>...</pre><p>Now, if all goes well, you can run this command from the console:</p><pre>npm run dev</pre><p>And after a few seconds you should see this show up in the console: event — compiled successfully. This is your queue that you can go to your browser and navigate to <a href="http://localhost:3000.">http://localhost:3000</a>. The output should be like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*6G2eSjILGaSxI8n2KYuqDg.png" /><figcaption>Your initial render should be like this.</figcaption></figure><p>At this point you have a working environment of Next.js with a very simple home page. From here we will be using Next.js’s getStaticSideProps function to query the HealthCare.gov API. Let’s get these logic in place.</p><p>We will create an uncomplicated articles index in a regular HTML Table. For now let’s add the skeleton of our app using with these placeholders in our index file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/353e353111a30632208ee55e523ee947/href">https://medium.com/media/353e353111a30632208ee55e523ee947/href</a></iframe><p>We will be using Next.js built-in tools for performance measurement. This is very easy to accomplish by creating a custom app file. For this create a file src/pages/_app.jsx and add the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a37e1584c7c2e847cf25799081dbddb1/href">https://medium.com/media/a37e1584c7c2e847cf25799081dbddb1/href</a></iframe><p>Now if we reload our index page in a browser you’d see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*89fXqnADj59P2y17UCPiGg.png" /><figcaption>Basic home page.</figcaption></figure><p>Not very exciting at this point. However, one important thing to notice is, in the console, you’ll see the item value: 15.56, which defines how long it took for the page to hydrate on Next.js. We will be referring to this value to measure the success of our performance optimizations. This number is expressed in milliseconds.</p><p>This page loads very fast but, of course, this is only a static page, no remote server fetching is involved at this point. Let’s move and interact with HealthCare.gov API.</p><h4>Step 2: Connecting to a remote API: HealthCare.gov</h4><p>HealthCare.gov has a very simple open API that allows us to fetch their content and, according to their <a href="https://www.healthcare.gov/developers/">documentation</a>, “<em>so that innovators, entrepreneurs, and partners can turn it into new products and services</em>”. Let’s do that.</p><p>We will connect to an end-point that will return a list of recent articles from HealthCare.gov. URL for this API is <a href="https://www.healthcare.gov/api/articles.json">https://www.healthcare.gov/api/articles.json</a>. The returned document is of type JSON, which is great news since Next.js understands JSON out of the box.</p><p>Additionally, we will install a new package, react-uuid, to uniquely identify iterative items within JSX loops, it uses 128-bit numbers.</p><pre>npm i -SD react-uuid</pre><p>Let’s rewire our index.jsx file as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d201d2d631cba02f6771732270010812/href">https://medium.com/media/d201d2d631cba02f6771732270010812/href</a></iframe><p>A few things are happening here. getStaticProps will fetch the information needed for the page before sending it to the client. This function also calls another function, fetchData, which is the one that does the heavy work of actually connecting to the API.</p><p>The other thing that is worth mentioning is that now the Home component receives a props argument, which is de-structured into a single articles variable. Then, this variable is used and iterated through in the returned JSX code. Notice the uuid() method call that will guarantee the uniqueness of each row when we run the loop.</p><p>Then, our rendered page will end up looking like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A6Km53B7h9rgotfkOecqFw.png" /><figcaption>Rendered page connecting to HealthCare.gov API.</figcaption></figure><p>Aha! We now have some real articles rendered. Notice our hydration value ballooned up to 53.49. This is, in all fairness, really fast, but let’s be clear that this is almost 4 times our previous static page value.</p><p>It would make sense to store this response and keep it for a sensible amount of time so that we don’t have to request it from HealthCare.gov servers on each page reload. Let’s throw Redis into the mix.</p><h4>Step 3: Installing Redis</h4><p>Redis is generally used as an in-memory cache for fast access to key-valued data. But Redis is so much more. It can also be used as a regular database, as a message broker, and even can work in replication in a cluster. For simplicity sake, in this article we will use Redis as an in-memory cache storage where we will save the responses from HealthCare.gov API.</p><p>A very easy way to install Redis is with Docker containers. Why? You only need to run this command:</p><pre>docker run -p 6379:6379 --name my-redis -d redis</pre><p>And you’re all done. You have a running instance of Redis locally and accessible at port 6379.</p><p>Of course, be mindful that, if you kill the my-redis container, you will lose your data. This is not a big deal at the moment, since we are using Redis as an in-memory cache, meaning that in it we will be storing volatile data only.</p><h4>Step 4: Caching the API results</h4><p>The fun part is next. We will make our running Redis instance act as a “middle man” between HealthCare.gov API and our app. Before fetching data remotely, our app will confirm with Redis if the data is already living locally in-memory. This operation is often called checking for a ‘cache hit-miss’.</p><p>Let’s kick it off by installing a Redis npm package, there are a bunch around. The one we are going to use is the one plainly called <a href="https://www.npmjs.com/package/redis">redis</a>. Also we are installing <a href="https://www.npmjs.com/package/bluebird">bluebird</a>, a library that allows us to ‘promisify’ all redis methods (redis npm package will support promises in version 4).</p><pre>npm i -S redis bluebird</pre><p>So, we need to update our index file like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00ef35704237bef0148f3dce39c16414/href">https://medium.com/media/00ef35704237bef0148f3dce39c16414/href</a></iframe><p>Most exciting things are happening inside the getStaticProps method. With bluebird.promisifyAll we effectively create shadow methods with the ending -Async, plus all of them return a promise now. So, cache.get() now becomes cache.getAsync(), additionally you can attach the await keyword in front of it. Again, when redis packages version 4.0 gets released, you can skip this step.</p><p>And then, a little logic which just checks if the key exists in our cache database; if it doesn’t (<em>a cache miss</em>) then we go and fetch it from the HealthCare.gov API servers. If the key is found (<em>a cache hit</em>), then we just go ahead and get that value, without fetching data from the remote server.</p><p>A little bit JSON.stringify and JSON.parse acrobatics are needed, since we are storing the JSON response from the API as a plain string.</p><p>The output in the browser should be exactly the same:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZdPv57gsxzuTLUM_xtSWCg.png" /><figcaption>Output of our articles list, from Redis cache.</figcaption></figure><p>Notice how the first time you will be connecting to the remote API, subsequent reloads will not connect to the remote server and will be using the cached version of the response JSON.</p><p>In this particular example, we got a response with a Next.js hydration value of 30.57, which almost cuts in half the total hydration time when connecting to the remote server. Now, this is a very simple, almost naïve example, so there will be a big margin of variance in our hydration time. For a more robust and complete application the optimization and time saving will be more visible.</p><p>This is all good and works, however, what if HealthCare.gov publishes a new article? Unfortunately, with our setup, this article will not be seen in our app, since our cache prevents us from refreshing our articles list with new publications. It is at this point that you want to try some good-ole cache invalidation techniques.</p><h4>Step 5: Invalidating cache results</h4><p>As mentioned earlier, cache invalidation is one of the most challenging tasks you could encounter in computer science. There are several techniques, one more complex than the previous. For our case, we will go with a simple cache expiration technique.</p><p>For this, we will use a new key in our Redis database, to avoid messing up with the previous articles key. For this example we will use exp-articles.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d4a745bbce93fbfb7174e1fd045ed4e/href">https://medium.com/media/6d4a745bbce93fbfb7174e1fd045ed4e/href</a></iframe><p>The other adjustment we need to do is to add the extra &#39;EX&#39; and 60 * 60 as the third and fourth parameters of the cache.set() method. The &#39;EX&#39; parameter just flags that this key will have an expiration date, while the last one multiplies 60 seconds by 60, in other words, this key will expire in 1 hour.</p><p>With this, we have made it so that our cached key will expire every hour, and so, we will have fresh content from the remote server constantly. This expiration number should be a value that makes sense for your business without compromising the integrity of the content or the cache lifespan.</p><h4>Additional optimization tasks</h4><p>While you can store binary data in a Redis Database –which means you can cache images, scripts, PDF files–, you may want to use a specific tool to cache binary files, like as a high performance HTTP Accelerator, such as <a href="https://varnish-cache.org/">Varnish</a>. If you use Varnish to speed up your binary files HTTP transfers, you can see improvements up to hundreds of times in faster downloads:</p><blockquote>“Varnish Cache is really, really fast. It typically speeds up delivery with a factor of 300–1000x, depending on your architecture.”</blockquote><blockquote>– <a href="https://varnish-cache.org/intro/index.html#intro">Varnish Introduction</a></blockquote><p>Having Redis Store targeted sections of your site –<em>articles, quick relatively volatile statistics, session management</em>– while at the same time implementing a Varnish Cache to return your assets –<em>images, almost-static scripts or stylesheets, SVG graphics, videos</em>– will more likely make your site extremely fast and available.</p><p>Another improvement you can make is that, both Redis and Varnish can work in clusters, meaning you can have several instances of your in-memory database. A common practice is to have one or several read-only instances while updates and writes will be handled by a master instance.</p><p>Given the current cloud-based-serverless world we are living in now, it would be fairly easy to kick-off a Redis Databases farm, dockerize each instance and allow them to be privately accessed by your app or web services.</p><h3>What’s Next and Further Reading</h3><p>Learn more about performance and speeding up your website:</p><ul><li><a href="https://uxdesign.cc/the-importance-of-perceived-performance-for-a-successful-user-experience-ac2f428887f9">The importance of ‘perceived performance’ for a successful user experience</a></li><li><a href="https://uxdesign.cc/user-oriented-web-architecture-heal-the-relationship-with-your-user-first-the-rest-will-follow-3d4b65b98ae1">User-oriented web architecture: heal the relationship with your user first, the rest will follow</a></li><li><a href="https://medium.com/swlh/implementing-known-design-patterns-in-typescript-delegation-observer-and-interceptor-b18ea385f4c6">Implementing Known Design Patterns in TypeScript: Delegation, Observer, and Interceptor</a></li></ul><p>Further reading:</p><ul><li><a href="https://redis.io/documentation">Redis Official Documentation</a></li><li><a href="https://varnish-cache.org/">Varnish HTTP Accelerator</a></li><li><a href="https://nextjs.org/docs">Official Next.js ‘Getting Started’ page</a></li><li><a href="https://www.healthcare.gov/developers/">HealthCare.gov API documentation</a></li></ul><h3>Thanks for reading!</h3><p>Find me on <a href="https://www.linkedin.com/in/pablo-del-valle">LinkedIn</a>, <a href="https://medium.com/@pablo.delvalle.cr">Medium</a>, <a href="https://github.com/delvalle">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5103976de188" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/implementing-a-simple-redis-cache-with-next-js-5103976de188">Implementing a Simple Redis Cache With Next.js</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The importance of ‘perceived performance’ for a successful user experience]]></title>
            <link>https://uxdesign.cc/the-importance-of-perceived-performance-for-a-successful-user-experience-ac2f428887f9?source=rss-3114c92aac3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac2f428887f9</guid>
            <category><![CDATA[user-experience]]></category>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[product-design]]></category>
            <dc:creator><![CDATA[Pablo A. Del Valle H.]]></dc:creator>
            <pubDate>Sat, 15 Aug 2020 04:19:48 GMT</pubDate>
            <atom:updated>2020-08-17T11:22:53.580Z</atom:updated>
            <content:encoded><![CDATA[<h4>Avoid keeping your users in a passive state by actively engaging their interests.</h4><figure><img alt="The perception of time varies and can be overestimated by extended resting phases." src="https://cdn-images-1.medium.com/max/1024/0*ZQGaecsHNK1cLNwl" /><figcaption>Photo by <a href="https://unsplash.com/@elisamichelet?utm_source=medium&amp;utm_medium=referral">Elisa Michelet</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="http://assets.eli.wtf/talks/perceived-perf-talk/#/">During a talk</a> at CSS Dev Conf, <a href="http://eli.wtf/">Eli Fitch</a> argued how people tend to perceive time in different ways and that, in essence, humans manage to overestimate waiting times, especially at rest, <a href="http://assets.eli.wtf/talks/perceived-perf-talk/#/19">up to 36%</a>. What does this mean?</p><p>In a nutshell, when a user hits that “Buy now” button each second that passes feels like three seconds for the average user. Psychologically the human brain has a hard time with patience and delaying gratification which, of course, maximizes any intrusion of friction and pain points. This, consequently, increases the stress levels for your customers.</p><p>While it pays off to have a codebase with 100% test coverage, a very well oiled compilation and building process, an optimized deployment operation, all this is something that none of your users care at the end of the day. The caveat is that all those “behind the scenes” development processes should be implemented and optimized, but let’s not forget the User Experience. Even if your site is statistically performing well, the real measurement you should account for is the <strong>users’ perceived performance</strong>.</p><p>Eli Fitch suggests to make the “passive phase less painful” or, in his own words, “<em>un-suck waiting time</em>”. Among his proposed action items to prevent the user feeling unease, my favorite one is to give the user a “sense of certainty”.</p><h4>Progress Bars and Spinners</h4><p>A study from <a href="https://www.chrisharrison.net/projects/progressbars2/ProgressBarsHarrison.pdf">Carnegie Mellon by Chris Harrison, Zhiquan Yeo and Scott E. Hudson</a> states that a <strong>progress bar</strong> makes the user feel time passing 12% faster and, more importantly, the effect of perceived acceleration increases as the waiting time lasts longer. Visual augmentations such as progress bars offer a sense of “something is happening” to the user.</p><p>As an additional benefit, having these visual cues will prevent the user from hitting the button more times, saving the network round trips of each canceled and restarted event. Also, could limit the potential of having “ghost transactions” in the database, from the inoffensive posting of a comment twice to the possibly more critical predicament of buying a product multiple times.</p><p>Incidentally, perhaps you wonder if a <strong>spinner</strong> should do the trick, and to be fair, it actually helps, however, spinners tend to occupy your user’s attention for a very short span of time. Fitch recommends to “cheat”, and expand your spinner with additional visual queues to keep your audience engaged. You could for instance implement a spinner that randomly changes shape, provides non-crucial text for the user to read while he waits, and changes slightly the layout.</p><h4>Animations</h4><p>Let’s not go back to the Internet of the 90s with flashing banners, blinking texts, pop-ups popping like carnival’s firecrackers. Having said that, a bit of animation <em>bling-bling</em> could improve the experience for your users.</p><p>Hitting a “Submit” button could very well just be a “Submit” button and nothing else, after all, it performs the submitting function quite well. However, you can augment that behavior by <strong>animating the button</strong> after being hit and perhaps showing a loading graphic, something to communicate to the user that a process is underway.</p><p>Overdoing it, of course, could potentially cause more harm than good. That’s why, according to <a href="https://sarahdrasnerdesign.com/">Sarah Drasner</a>, author of O’Reilly’s SVG Animations, suggests that any transition between two states of an element via animation should not exceed 300 milliseconds. Anything else above that threshold will feel janky and intrusive.</p><h4>Anticipate your User Actions</h4><p>Regular brick-and-mortar stores, especially the big-box ones, have the organization of the aisles, the position of products, even the music and lights of the place to a science. The neat configuration of all the shelves is just the aftermath of a carefully designed strategy that considers profitability of the product, storing capacity, warehousing and distribution and also consumer psychology. There is a reason why the salsa is placed right next to the chips. All this can be extrapolated to online Product Design and User Experience.</p><p>Predicting your User’s path through your site is one of the most important things you need to consider when designing your product. And this certainly overlaps with how you are going to develop your website.</p><p>Consider that you have identified that after each purchase, your customers tend to click two different links: ‘view orders’ and ‘similar products’. Having made such a discovery is enormous because now you can design the landing page after each purchase with these two routes highlighted, at the <a href="https://web.dev/first-contentful-paint/">first contentful paint</a>, prioritized and, as Eli Fitch notes, everything else can be lazy-loaded or moved to a ‘below the fold’ position.</p><p>Acknowledging these patterns allows us to anticipate what your users will do next and maybe even have it loaded before they get there, providing a more natural, seamless experience.</p><h4>Prioritize the User Experience above the Developer Experience</h4><p>A common pitfall for many digital companies is to forget that their whole business should be centered in the User and the User Needs. It is quite prevalent to see oversized Javascript files sent to every page without considering bundle optimization or progressive loading just because “it was so much easier for the dev team to keep it all in one file”.</p><p>Maybe implementing an extra build job during compilation to analyze the size of your images might be an inconvenience or a nuisance for the development team, more waiting for the whole build to end successfully, but that extra step will prove to be invaluable when your site is deployed and consumed by your end users.</p><p>During <a href="https://reactpodcast.com/episodes/97">episode 97</a> of the <a href="https://reactpodcast.com/">React Podcast by Michael Chan</a>, guest <a href="https://twitter.com/tlakomy/">Tomasz Łakomy</a> posed the “controversial” idea that statistically if 100 users are going to order a pizza online tonight, 100% of those hungry customers do not care if the pizza site they are ordering from has all their unit tests passing. End-user customers just don’t care.</p><p>However they do care if the site got their address correctly if their order was taken accurately if they were able to pay using various payment methods.</p><p>The takeaway key here is that development workflows should be improved, revamped and upgraded often, but not in lieu of the User Experience, analyzing the behavior of your users, giving them exactly what they need, when they need it.</p><p>Always consider that your main focus should be the actual end-user of your site, leverage your knowledge with data science, analysis and smart implementations.</p><h3>What’s Next and Further Reading</h3><p>Learn more about Behavior-Driven Development and User-Oriented Web Architecture:</p><ul><li><a href="https://medium.com/swlh/is-behavior-driven-development-right-for-your-project-462e9371516d">Is Behavior-Driven Development right for your Project?</a></li><li><a href="https://uxdesign.cc/user-oriented-web-architecture-heal-the-relationship-with-your-user-first-the-rest-will-follow-3d4b65b98ae1">User-oriented web architecture: heal the relationship with your user first, the rest will follow</a></li></ul><p>Thanks for reading! Find me on <a href="https://www.linkedin.com/in/pablo-del-valle">LinkedIn</a>, <a href="https://medium.com/@pablo.delvalle.cr">Medium</a>, <a href="https://github.com/delvalle">GitHub</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/94/0*9fn4A0ZEhutxOuBr" /><figcaption>The UX Collective donates US$1 for each article published in our platform. This story contributed to <a href="https://www.bayareablackdesigners.com/">Bay Area Black Designers</a>: a professional development community for Black people who are digital designers and researchers in the San Francisco Bay Area. By joining together in community, members share inspiration, connection, peer mentorship, professional development, resources, feedback, support, and resilience. Silence against systemic racism is not an option. Build the design community you believe in.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac2f428887f9" width="1" height="1" alt=""><hr><p><a href="https://uxdesign.cc/the-importance-of-perceived-performance-for-a-successful-user-experience-ac2f428887f9">The importance of ‘perceived performance’ for a successful user experience</a> was originally published in <a href="https://uxdesign.cc/">UX Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is the difference Between a Mock and a Stub?]]></title>
            <link>https://medium.com/swlh/what-is-the-difference-between-a-mock-and-a-stub-bd6b639e9fa5?source=rss-3114c92aac3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd6b639e9fa5</guid>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Pablo A. Del Valle H.]]></dc:creator>
            <pubDate>Tue, 11 Aug 2020 06:18:18 GMT</pubDate>
            <atom:updated>2020-08-11T23:05:25.216Z</atom:updated>
            <content:encoded><![CDATA[<h4>Often you’ll see Mocks and Stubs called interchangeably, however they are different, and sometimes not used correctly</h4><figure><img alt="Learn the difference between a Mock and a Stub when testing" src="https://cdn-images-1.medium.com/max/1024/0*KizTFFnbInPq8fTI" /><figcaption>Photo by <a href="https://unsplash.com/@myphotocave?utm_source=medium&amp;utm_medium=referral">Raghav Bhasin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Test-Driven Development relies heavily upon properly defining business cases where the requirements are translated to Test Units which derivate in short development cycles that promote the code to pass the tests one by one.</p><p>This philosophy of development presents itself as a challenge for many developers who are used to a more <em>rapid</em>-like development process in which the achievement of discernible goals takes precedence over a well-thought software architecture (as opposed to the <em>measure twice cut once</em> so to speak).</p><p>In that vein, it’s important to grasp the key concepts of a test-centered development. Two definitions that often get confused and sometimes are used interchangeably are Mocks and Stubs. Let’s dig deeper into the concepts of each and how they measure and contrast each other.</p><p>Semantically speaking, a Unit Test should concentrate on a single fragment (or <em>unit</em>) of a system. Yet, more often than not, you can’t test a single piece of your software without the aid of external elements, be a call to a third-party module, a database, or even another class that lives within your own codebase. In order for us to appropriately test the correctness of functionality, we will implement a representation (often called <em>fakes</em> or <em>doubles</em>) of these external element’s behaviors, responses, datasets, etc.</p><p>Stubs, traditionally, deliver a response for a call that was predetermined within the test. In other words, when a Test calls for a Stub, the response send back was actually engineered to accommodate the test, no actual connections were made to another web service or database, no logical computation was done internally, it just provides an expected response –or a <strong>state</strong>.</p><p>Meanwhile, a Mock deals more directly with the <strong>behavior</strong> of whatever it represents. You will usually see a Mock performing a bit of logic in it to adhere more closely to the object it is mocking.</p><p>At this point, I need to make a distinction between State validation and Behavior validation.</p><h4>State validation and Behavior validation</h4><p>A State validation asserts that the value of a property, a variable, or response is equal to the expectation. An example of this might be to verify that a function returns the value we want, or perhaps that we receive the expected recordset when querying a database.</p><p>Meanwhile, a Behavior validation arguably will go further than the State validation, because it will also check if the actions and events expected to be triggered by the Test were set off. An example of a Behavior validation is to assert if a method has been called.</p><p>Mocks always validate behaviors. Stubs can verify behaviors as well, but then their name change to <em>Spies</em>.</p><h4>Planning our Business Case</h4><p>Let’s assume that our business case is one financial software that holds account balances. For simplicity&#39;s sake, let’s assume a naïve function that withdraw()s an amount from the customer’s balance. The outcome can be twofold: if the balance is greater than the withdrawal amount, then the amount is deducted from the balance. If the withdrawal amount is greater than the balance, then nothing happens and the balance is kept the same.</p><p>Let’s see this using Python. It will be easy to follow even if you are not familiar with Python.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/596dc1364c1d5cdc866a0d2efa0ffad6/href">https://medium.com/media/596dc1364c1d5cdc866a0d2efa0ffad6/href</a></iframe><p>Here you can easily see we created two Tests (plus a setUp() method): the first one –test_withdraw_has_balance()– will validate our use case when the customer has enough balance while the second one –test_withdraw_not_enough_balance()– checks the case when the customer has less balance than the withdrawal amount.</p><p>If you are curious about the class that we are testing, here it is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9bdca1acda2410aa83c5e553a5fa88a/href">https://medium.com/media/c9bdca1acda2410aa83c5e553a5fa88a/href</a></iframe><p>Now, speaking about the two Unit Tests we are starting with, both are actually validating the State of the account’s balance. However, both are testing with the actual methods of the Account class –the real thing. Let’s try and test using a Stub.</p><h4>Using a Stub</h4><p>In this case we will Stub the get_balance() method. This way we will guarantee that it will return a controlled value, in our example, 60.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6b4705e098ffea1be5526eb657a3b3a/href">https://medium.com/media/d6b4705e098ffea1be5526eb657a3b3a/href</a></iframe><p>Notice how we replaced the original get_balance() method with our Stub (line 9). Then when we want to assert its value (line 18) we will be getting the correct value. This Stub case is quite simple and probably unnecessary, but I think is an easy enough example to showcase how a Stub would work.</p><p>Important to notice is that we reestablished the get_balance() method in the finally: part of our try-catch, this can also be achieved in thetearDown() method.</p><p>We can also check the Behavior of the process of updating the balance by asserting that the update_balance() method was called. For this, we will be using a Mock.</p><h4>Using Mocks</h4><p>At last, we can check if the Behavior of entering a withdrawal is correct using Mocks. For this, notice how we import the Magic_Mock helper from the unittest.mock library.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0e9398e3e7bf180054b4eb09d75715b/href">https://medium.com/media/f0e9398e3e7bf180054b4eb09d75715b/href</a></iframe><p>To keep it short, I did not restore the update_balance() method, you can do that if you want in the test itself like we did in the Stub example or using thetearDown() method.</p><p>Here, again we replaced a method in our class, in this case, the update_balance() method. However rather than testing the return value of get_balance(), we are asserting that the internal method that updates the balance was called. In this case, we can even verify that the argument sent to the method is what we expect it to be, which is 25 (100–75). Thus we are verifying the Behavior of our class.</p><h4>So which one is better?</h4><p>As much as I would love to say with confidence “<em>this is the way to go</em>”, the truth is that you should analyze your cases individually and decide if you want to test using Stubs or Mocks.</p><p>On the one hand, Stubs tend to be closer to the Unit Test ideology of detaching the Unit of work that you want to test. By Stubbing your resources, you are effectively disconnecting your Tests from any possible side effects of an outsider. On the other hand, eventually, as your codebase grows, you will find that updates in the implementation of a method could swell into a cascade of changes in your Stubs.</p><p>When you Mock your outside resources, it helps you think in a more holistic way and evaluate the interactions between the domains of your software. Also, and probably in a more practical sense, they can help you achieve higher coverage over intricate pieces of code that normally won’t get tested often or more than once. One downside of Mocking is that you are, at some level, coupling your Tests with outside functionality, breaking the boundaries of your Unit Tests.</p><p>In practice, it’s probably a good idea to go with a combination of the two, considering your cases one by one.</p><h3>What’s Next and Further Reading</h3><p>Learn different ways to expand and leverage your knowledge in code testing:</p><ul><li><a href="https://medium.com/swlh/javascript-testing-jest-spies-and-mocks-add0048ba345">Javascript Testing: Jest Spies and Mocks</a></li><li><a href="https://levelup.gitconnected.com/configuring-jest-for-next-js-react-and-babel-from-scratch-bb3b7751329b">Configuring Jest for Next.JS (React) and Babel from scratch</a></li><li><a href="https://medium.com/swlh/is-behavior-driven-development-right-for-your-project-462e9371516d">Is Behavior-Driven Development right for your Project?</a></li><li><a href="https://uxdesign.cc/user-oriented-web-architecture-heal-the-relationship-with-your-user-first-the-rest-will-follow-3d4b65b98ae1">User-oriented web architecture: heal the relationship with your user first, the rest will follow</a></li></ul><h3>Thanks for reading!</h3><p>Find me on <a href="https://www.linkedin.com/in/pablo-del-valle">LinkedIn</a>, <a href="https://medium.com/@pablo.delvalle.cr">Medium</a>, <a href="https://github.com/delvalle">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd6b639e9fa5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/what-is-the-difference-between-a-mock-and-a-stub-bd6b639e9fa5">What Is the difference Between a Mock and a Stub?</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Known Design Patterns in TypeScript: Delegation, Observer, and Interceptor]]></title>
            <link>https://medium.com/swlh/implementing-known-design-patterns-in-typescript-delegation-observer-and-interceptor-b18ea385f4c6?source=rss-3114c92aac3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b18ea385f4c6</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[programming-pattern]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Pablo A. Del Valle H.]]></dc:creator>
            <pubDate>Fri, 12 Jun 2020 03:40:05 GMT</pubDate>
            <atom:updated>2020-06-12T18:19:23.207Z</atom:updated>
            <content:encoded><![CDATA[<h4>Delegation, Observer, and Interceptor design patterns have been around for years. Unsurprisingly, they made their way into the TypeScript-sphere</h4><figure><img alt="TypeScript allows developers to implement many of the good ole design patterns, such as Delegate, Observer, and Interceptor." src="https://cdn-images-1.medium.com/max/1024/0*hd5PxNL2WFYFcAqL" /><figcaption>Photo by <a href="https://unsplash.com/@ryanquintal?utm_source=medium&amp;utm_medium=referral">Ryan Quintal</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Software Design Patterns have been around for a long time, arguably, since the 1960s they emerged as <strong>formalized, structured programming practices that allow a faster and more efficient solution by implementing proven and reusable coding paradigms</strong>.</p><blockquote>If you are interested, you can read “Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley Professional Computing Series)”. This 1994 book set a standard for defining what a design pattern is, its application and also introduced several design patterns still in use today; certainly the ones talked about in this article were discussed in Design Patterns book.</blockquote><p>TypeScript is fairly recent, having been created in 2012. However, we can implement some of those proven patterns in it, and this is not a surprise, considering that the creator of Delphi and Turbo Pascal programming languages, <a href="https://twitter.com/ahejlsberg">Anders Hejlsberg</a>, is one TypeScript core engineers.</p><p>But how much can we accomplish in software design patterns with a JavaScript superset such as TypeScript? As it turns out, quite a lot. Let’s go through 3 of them: <strong>Delegation</strong>, <strong>Observer</strong>, and <strong>Interceptor</strong> patterns.</p><h4>Delegation Design Pattern</h4><p>You might have already implemented the Delegation Pattern at some in your career without even knowing. And that is precisely the point. Not fully understanding the concept behind this seemingly simple pattern will help boost your application efficiency.</p><p><strong>So, what is a Delegation Design Pattern</strong>? Essentially, what you have is <strong>a first-level object that receives a request and delegates said action to a second-level object</strong>. Traditionally, the delegate (the second-level “utility object”) will act on behalf of the requesting object, meaning that the context of the second object will act as if it was the first object. I won’t go into the nuances of the Forwarding Pattern vs. the Delegation Pattern so, for the sake of keeping things simple, let’s stick to this definition.</p><p>First, let’s see how our Delegation Architecture will work. We are going to implement a simple <strong>Customer</strong> =&gt; <strong>Bank</strong> (with <strong>Card</strong> &amp; <strong>Savings</strong> Accounts). The Delegation will be executed via a <strong>Transaction</strong> class.</p><figure><img alt="Delegation Design Pattern" src="https://cdn-images-1.medium.com/max/1024/1*_PUavV4x2UhOObctEgNZDA.png" /><figcaption>Delegation Design Pattern</figcaption></figure><p>Let’s jump into the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd53a6eb8c22aec298b76839ec1234ec/href">https://medium.com/media/fd53a6eb8c22aec298b76839ec1234ec/href</a></iframe><p>Something that might be apparent at this point is that the <strong>delegated transaction is being executed onto the object that requires the action</strong> as opposed to calling a method passed down from inheritance. This allows us to keep that <strong>delegated business logic separated from our main class structure</strong>, while at the same time having the events being called <strong>on the original context</strong>.</p><p>In our example, the execution of the transaction delegation is pulled out of the set of classes that we have and is being fulfilled in the external delegate Transaction class, which can <strong>enforce security policies</strong>, <strong>isolates peripheral actions</strong> such as logging and reporting, <strong>perform validation</strong>, and many more that, will only pollute the taxonomy of our current classes.</p><h4>Observer Design Pattern</h4><p>A fundamental concept to understand the Observer Design Pattern is the idea of subscribers and notifications. In principle, an<strong> Observer will watch on the value of a variable</strong> (it’s <em>subscribed</em> to it) and, once this value changes, it will <strong>dispatch a notification</strong> that will be <em>broadcasted</em> <strong>to other objects</strong>.</p><p>The pattern provides a way to subscribe or unsubscribe from these observers, traditionally via <strong>on</strong>/<strong>off </strong>or <strong>attach</strong>/<strong>detach</strong> <strong>methods</strong>. Control of the subscription of the Observers is crucial for preventing an overflow of memory, where Observers keep running in the background in a “zombie” state.</p><p>React implements an Observer of sorts on its Lifecycle methods, except they can’t be unsubscribed, they are triggered regardless of someone listening or not. But, when you write a Hook with a dependency of a Prop, naturally, you are Observing this Prop value, and your callback method, in the first parameter of the Hook, is called upon update.</p><pre>useEffect(() =&gt; {<br>  <strong>// ... do something with currentDate value ...</strong><br>}, [ <strong>currentDate</strong> ]);</pre><p>In our particular example, a good place to add an observer would be for the account balances. Let’s assume that every time the balance in either your card or savings account changes, the system will send out an email to the customer detailing the transaction.</p><figure><img alt="Observer Design Pattern" src="https://cdn-images-1.medium.com/max/1024/1*ceXEMsfaf0TR1dci-mIsUQ.png" /><figcaption>Observer Design Pattern</figcaption></figure><p>Let’s look at the Observer code. Mind you, this is just one implementation, there are many ways this pattern can be done.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cd365d77a272e5338d421dce328dfe2/href">https://medium.com/media/1cd365d77a272e5338d421dce328dfe2/href</a></iframe><p>With this, we just need to update our Account class. Like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d3743bfb4118959b94d20715d882b63/href">https://medium.com/media/3d3743bfb4118959b94d20715d882b63/href</a></iframe><p>What we have done here is, first, created a private _observers variable where we are going to store any observers related to this class. We could have just as easily created a global observers repository (maybe through a singleton instance or keeping it in a global provider) but, for the sake of the simplicity of our example, let’s just keep it as a member of the Account class.</p><p>The next thing you’ll notice is the <strong>subscription</strong> to a new observer right in the constructor. The argument send for this Observer is just a plain string that identifies what the observer is. An optional second parameter will be a callback function to provide additional actions.</p><p>Finally, the most suitable place to execute the notification of our observer would have to be the <strong>setter</strong>. This notifier will receive two arguments, the first one being the subject (established in the constructor when the Observer was created) and the new value that this observed variable will be receiving.</p><p>At this point, any time the balance is changed, the Observer will be notified, and the message will be broadcasted appropriately.</p><h4>Interceptor Design Pattern</h4><p>Not surprisingly, the Interceptor Design Patter will <strong>catch a communication stream and modify or augment the payload</strong> based on certain defined business logic. The way this pattern is established is without any side effects, in other words, neither the receiver nor the sender needs to change their interface.</p><p>This pattern is often called the <strong>Middleware pattern</strong> since it occurs in the middle of the communication between the client and the end-point. Middlewares are very common in web applications, such as in webservers and microservices.</p><figure><img alt="Interceptor Design Pattern" src="https://cdn-images-1.medium.com/max/1024/1*NY89dWexkiELn-vGtVvkzQ.png" /><figcaption>Interceptor Design Pattern</figcaption></figure><p>A traditional way to achieve this is by the use of <strong>Decorators</strong> which, in effect, expands the functionality of the method being decorated. TypeScript does support the use of decorators, however, their usage is considered “<em>experimental</em>” and thus, they need to be enabled in the <strong>tsconfig.json</strong>.</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    ...<br>    <strong>experimentalDecorators&quot;: true,</strong><br>    ...<br>  }<br>}</pre><p>Now, we will implement a simple @fee factory decorator, which will receive a parameter for the amount this transaction should charge the customer for.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80728058ec75b719b1589360da94eb3d/href">https://medium.com/media/80728058ec75b719b1589360da94eb3d/href</a></iframe><p>Having created our decorator, we just need to modify our setter to have @fee(10) before its definition, where the parameter sent establishes that each transaction will charge an additional $10 to our customer. Additional logic can be applied to either modify the fee per purchase total ranges or exempt some transactions, or maybe even applying discounts.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a8694277bdf00b257a3ea69f612ec46/href">https://medium.com/media/3a8694277bdf00b257a3ea69f612ec46/href</a></iframe><p>Effectively, every time the balance setter gets called, the @fee decorator will trigger the functionality we want by <strong>intercepting</strong> the communication and performing the event of adding the extra charge.</p><p>More subjects that you can explore:</p><ul><li><a href="https://medium.com/@pablo.delvalle.cr/typescript-generic-types-and-how-to-properly-implement-them-498519a8ab65">TypeScript Generic Types and How to Properly Implement Them</a></li><li><a href="https://medium.com/@pablo.delvalle.cr/typescript-reactjs-the-element-vs-reactelement-vs-htmlelement-vs-node-confusion-6cda21315ddd">TypeScript / ReactJS: The Element vs. ReactElement vs. HTMLElement vs. Node confusion</a></li><li><a href="https://medium.com/swlh/graphql-orm-with-typescript-implementing-apollo-server-express-and-sqlite-5f16a92968d0">GraphQL ORM with TypeScript implementing Apollo Server(Express) and SQLite</a></li><li><a href="https://medium.com/@pablo.delvalle.cr/react-lifecycles-with-hooks-explained-704c3eaf2706">React Lifecycles with Hooks Explained</a></li></ul><p>Further reading:</p><ul><li><a href="https://www.typescriptlang.org/docs/">TypeScript official documentation</a></li></ul><h3>Thanks for reading!</h3><p>Find me on <a href="https://www.linkedin.com/in/pablo-del-valle">LinkedIn</a>, <a href="https://medium.com/@pablo.delvalle.cr">Medium</a>, <a href="https://github.com/delvalle">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b18ea385f4c6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/implementing-known-design-patterns-in-typescript-delegation-observer-and-interceptor-b18ea385f4c6">Implementing Known Design Patterns in TypeScript: Delegation, Observer, and Interceptor</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript Generic Types and How to Properly Implement Them]]></title>
            <link>https://medium.com/swlh/typescript-generic-types-and-how-to-properly-implement-them-498519a8ab65?source=rss-3114c92aac3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/498519a8ab65</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[how-to]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[generic-types]]></category>
            <dc:creator><![CDATA[Pablo A. Del Valle H.]]></dc:creator>
            <pubDate>Wed, 10 Jun 2020 15:04:40 GMT</pubDate>
            <atom:updated>2020-06-11T03:07:57.514Z</atom:updated>
            <content:encoded><![CDATA[<h4>Generic Types are a powerful TypeScript tool often misused due to them being so different from what a developer coming from traditional JavaScript is used to</h4><figure><img alt="Learn TypeScript’s Generic Types and their usages" src="https://cdn-images-1.medium.com/max/1024/0*SoJZZl9tIjXUBIp-" /><figcaption>Photo by <a href="https://unsplash.com/@ilmatar?utm_source=medium&amp;utm_medium=referral">Iza Gawrych</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In TypeScript, Generic Types enable us to define a placeholder type for a variable we do not know enough yet to precise its type. Consider the following snippet:</p><pre>const sayMessage = (message: string): string =&gt; `Simon says ${message}`;</pre><p>The previous function will work quite well if we are sure that the argument send, when <strong>sayMessage</strong> is called, will always be a <strong>string</strong>. However, there might be situations that could prevent that to happen. For example, the <strong>message</strong> argument is <strong>coming from a third party</strong>, say a service, database, input field, etc. Another, reason why this might cause issues, later on, is the possibility of the <strong>design of the application changes</strong>, and suddenly it’s supposed to accept numbers.</p><p>Let’s take on the last condition. Let’s assume we received a change request to allow the <strong>sayMessage</strong> function to, in addition to strings, receive also numbers. Maybe our first hunch is to do something like this:</p><pre><em>// extending the parameter type scope with a Union type</em></pre><pre>const sayMessage = (message: string <strong>| number</strong>): string =&gt; `Simon says ${message}`;</pre><p>And that would work. After all, that’s what <strong>Union Types</strong> are for. However, I’d argue that this is a poor architectural pattern and should be used sparingly and only on punctual cases; since this approach, as a result, leaves our simple function <strong>not suitable to scale</strong>. Say that a new request comes in, asking to allow <strong>null</strong> values to be accepted as parameters:</p><pre><em>// not the best approach</em></pre><pre>const sayMessage = (message: string <strong>| number | null</strong>): string =&gt; `Simon says ${message}`;</pre><p>You might even be tempted to try this:</p><pre><em>// not the best approach</em></pre><pre>const sayMessage = (message: <strong>any</strong>): string =&gt; `Simon says ${message}`;</pre><p>Well… at this point, I bet you start to feel a little bit uneasy on your initial hunch. <strong>There is a better solution.</strong></p><h4>Implementing Type Variables as Function Parameters</h4><p>A more elegant way to solve the aforementioned problem would be to implement <strong>Type Variables</strong> (otherwise known as “<strong>Generics</strong>”). Consider the following snippet:</p><pre><em>// leveraging a simple Generic Type<br>// as a function parameter (lambda)</em></pre><pre>const sayMessage = <strong><em>&lt;</em>T extends unknown<em>&gt;</em></strong><em>(</em>message: <strong>T</strong><em>)</em>: string =&gt; `Simon says $<em>{</em>message<em>}</em>`;</pre><p>So, a number of things going here. First, you’ll notice the <strong>&lt;T extends unknown&gt;</strong> right before the parameter list of the function. <strong>T</strong> is in fact the representation of the Generic Type. <strong>T</strong> is what traditionally is used for these Generic Types (<strong>T</strong> stands for Type), however, you can use whatever you want for the Generic Type name. The “<strong>extends unknown</strong>” bit has to be added for <em>lambda</em> functions, otherwise, you’ll get a syntax error. For example, <em>non-lambda</em> functions can define the exact same signature outlined previously as follows:</p><pre><em>// leveraging a simple Generic Type<br>// as a function parameter (non-lambda)</em></pre><pre>function sayMessage<strong>&lt;T&gt;</strong>(message: T):string {<br>  <strong>return</strong> `Simon says $<em>{</em>message<em>}</em>`;<br>}</pre><p>Just a different way to express the same sentiment. I personally prefer <em>lambda</em> functions, but to each it’s own!</p><p>The next thing we could point out is that our <strong>message</strong> parameter is not a <strong>string</strong> or a <strong>number</strong> or a <strong>string | number</strong> anymore, but rather a <strong>T</strong> type. This allows us to do the following:</p><pre>sayMessage(<strong>&#39;hello&#39;</strong>); <em>// returns &#39;Simon says hello&#39;</em><br>sayMessage(<strong>1</strong>);       <em>// returns &#39;Simon says 1&#39;</em><br>sayMessage(<strong>null</strong>);    <em>// returns &#39;Simon says null&#39;</em></pre><p>All previous examples are valid since <strong>sayMessage</strong> now accepts Generic Type arguments.</p><p>One cool thing about using Generic Types is that the type of the parameter can also be used within the body of the function and even be returned:</p><pre><em>// returning the generic type<br>// in the return expression of the function</em></pre><pre>const sayMessage = <em>&lt;</em>T extends unknown<em>&gt;(</em>message: T<em>)</em>: <strong><em>[ </em>string, T <em>]</em></strong><em> </em>=&gt; <strong><em>[<br>  </em>`Simon says $<em>{</em>message<em>}</em>`,<br>  message,<br><em>]</em></strong>;</pre><pre>sayMessage(&#39;hello&#39;); <em>// returns [ &#39;Simon says hello&#39;, &#39;hello&#39; ]</em></pre><p>The previous code will return a <em>tuple</em> comprised of the composed string (<em>Simon says “T variable”</em>) and the actual <strong>&lt;T&gt;</strong> parameter passed as the second argument.</p><h4>Constraining the Types in a Generic</h4><p>Our previous example of a generic parameter might be too broad and will allow the consumer of the function to call it sending in types such as <em>undefined</em>, <em>null,</em> or even an <em>object</em>. Let’s prevent that by using <strong>Generic Constraints</strong>.</p><p>Let’s limit how much the user of the function can send in:</p><pre><em>// Generic Constraints via extending keyof another type or variable</em></pre><pre><strong>enum messages {<br>  greeting = &#39;hello&#39;,<br>  farewell = &#39;bye&#39;,<br>  love = &#39;I love you&#39;,<br>}</strong></pre><pre>const sayMessage = <strong>&lt;M, T extends keyof M&gt;</strong>(<strong>messages: M, message: T</strong>): [ string, T ] =&gt; [<br>  `Simon says ${messages[message]}`,<br>  message,<br>];</pre><pre><em>// returns [ &#39;Simon says bye&#39;, &#39;farewell&#39; ]</em><br>sayMessage(<strong>messages</strong>, <strong>&#39;farewell&#39;</strong>);</pre><p>The special syntax of “<strong>T extends keyof M</strong>” is telling us that the parameter <strong>T</strong> is a member of the first parameter — type <strong>M</strong> — . So, essentially, we are constraining the possible options for this parameter to, in our example, 3 choices: ‘<strong>greeting</strong>’, ‘<strong>farewell</strong>’, or ‘<strong>love</strong>’.</p><h4>Using an Interface to constraint a Generic</h4><p>Another neat way to use a Generic Type is by implementing <strong>Interfaces</strong> which is also another way you can constraint the scope of your type. The following example is actually a 2 in 1 example:</p><pre><em>// Generic Constraints via interface extension</em></pre><pre><strong>interface IMessage&lt;M&gt; {<br>  message: M;<br>  emotion: string;<br>}</strong></pre><pre>const sayMessage = &lt;<strong>T extends IMessage&lt;string&gt;</strong>&gt;(<strong>message: T</strong>): [ string, T ] =&gt; [<br>  `Simon says <strong>${message.message}${message.emotion}</strong>`,<br>  message,<br>];</pre><pre><em>// returns [ &#39;Simon says welcome!&#39;, { message: &#39;welcome&#39;, emotion: &#39;!&#39; } ]</em><br>console.log(sayMessage(<strong>{ message: &#39;welcome&#39;, emotion: &#39;!&#39; }</strong>));</pre><p>First, we create an <strong>IMessage interface</strong>. This interface, in turn, implements a Generic Type (<strong>M</strong>). The interface is quite simple, establishing an object with two members: <strong>message</strong> (this is the generic type <strong>M</strong>) and an <strong>emotion</strong>, which is a string.</p><p>Then, our <strong>sayMessage</strong> function delineates that the parameter it receives (<strong>message</strong>) is a Generic Type that extends the <strong>IMessage</strong> interface. This ensures that this parameter will comply with the contract established there (requires to have a <strong>message</strong> and an <strong>emotion</strong>).</p><p>Notice the special notation for this Generic Type: &lt;<strong>T extends IMessage&lt;string&gt;</strong>&gt;, this ensures that the <strong>message</strong> member of the <strong>IMessage</strong> interface is a <em>string</em>.</p><h4>TypeScript’s Utility Types</h4><p>In TypeScript, you can actually see Generic Types being used in many places, as a matter of fact, there’s even have a specific <a href="https://www.typescriptlang.org/docs/handbook/utility-types.html">section for them in their documentation</a>.</p><p>For example, one of the preferred ways to <strong>define an Array</strong> in TypeScript makes use of Generics:</p><pre>let containers: <strong>Array&lt;HTMLTableElement&gt;</strong> = [];</pre><p>This definition, applying all the knowledge gained from this article, tells us that the variable <strong>containers</strong> will exercise the HTMLTableElement that was defined as a Generic Type within the Array’s interface for TypeScript, which has this signature:</p><pre>// Array&lt;T&gt; definition on TypeScripts source code</pre><pre>interface <strong>Array<em>&lt;</em>T<em>&gt;</em></strong><em> {<br>  ...<br>}</em></pre><p>Another built-in Generic Type you might find using a lot is the <strong>NonNullable</strong> one. This one gets defined as a custom type in TypeScript source code:</p><pre>type <strong>NonNullable<em>&lt;</em>T<em>&gt;</em></strong><em> </em>= T extends null | undefined ? never : T;</pre><p>Quite an interesting definition. Here we see a ternary conditional where, if whatever comes from the <strong>&lt;T&gt;</strong> type is an extension of either <strong>null</strong> or <strong>undefined</strong>, it will return a <strong>never</strong> type (“<strong>never</strong> types” deserve a whole new chapter of their own) essentially making it “impossible” to be either or <em>null</em> or <em>undefined</em>, otherwise, it will return the passed <strong>T</strong> type.</p><p>I’d encourage you to explore TypeScript built-in Utility types as they might save you architecture design as well as development time.</p><h4>Conclusion</h4><p>Generics are supported by many well-established programming languages such as C# or Java, it only <strong>makes sense to implement them in TypeScript</strong> as well.</p><p>One of the best use cases for Generics in TypeScript is to provide a <strong>type-safe variable for unknowns</strong>, such as retrieving <strong>API data sets</strong> or <strong>accepting user input</strong>. However, this is not the only use case:</p><ul><li>Provide better <strong>readability</strong> of your code</li><li>Help you <strong>catch unsuspected scenarios</strong> with unknown variables</li><li>Let your IDE give you <strong>better IntelliSense suggestions</strong></li><li>Assist TypeScript to <strong>properly consume otherwise non-type-safe data</strong> (API responses, user input, calculations, parsing a JSON file, etc.)</li><li>Keep you from assigning the ‘<strong><em>any</em></strong> type’ to unknown variables</li><li>Properly type your variable will also <strong>serve a pseudo documentation purpose</strong>, whereas you read the code and understand what the variables are used for</li></ul><p>More subjects that you can explore:</p><ul><li><a href="https://medium.com/@pablo.delvalle.cr/typescript-reactjs-the-element-vs-reactelement-vs-htmlelement-vs-node-confusion-6cda21315ddd">TypeScript / ReactJS: The Element vs. ReactElement vs. HTMLElement vs. Node confusion</a></li><li><a href="https://medium.com/swlh/graphql-orm-with-typescript-implementing-apollo-server-express-and-sqlite-5f16a92968d0">GraphQL ORM with TypeScript implementing Apollo Server(Express) and SQLite</a></li><li><a href="https://medium.com/@pablo.delvalle.cr/react-lifecycles-with-hooks-explained-704c3eaf2706">React Lifecycles with Hooks Explained</a></li><li><a href="https://levelup.gitconnected.com/oop-when-to-use-abstract-base-class-vs-interface-41509a43cd7">OOP: When to use `abstract` base class vs `interface`</a></li></ul><p>Further reading:</p><ul><li><a href="https://www.typescriptlang.org/docs/">TypeScript official documentation</a></li><li><a href="https://www.typescriptlang.org/docs/handbook/generics.html">TypeScript official Generics documentation</a></li></ul><h3>Thanks for reading!</h3><p>Find me on <a href="https://www.linkedin.com/in/pablo-del-valle">LinkedIn</a>, <a href="https://medium.com/@pablo.delvalle.cr">Medium</a>, <a href="https://github.com/delvalle">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=498519a8ab65" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/typescript-generic-types-and-how-to-properly-implement-them-498519a8ab65">TypeScript Generic Types and How to Properly Implement Them</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Element vs. ReactElement vs. HTMLElement vs. Node Confusion in TypeScript and React]]></title>
            <link>https://medium.com/better-programming/typescript-reactjs-the-element-vs-reactelement-vs-htmlelement-vs-node-confusion-6cda21315ddd?source=rss-3114c92aac3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cda21315ddd</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Pablo A. Del Valle H.]]></dc:creator>
            <pubDate>Tue, 09 Jun 2020 23:10:22 GMT</pubDate>
            <atom:updated>2020-06-10T17:49:19.359Z</atom:updated>
            <content:encoded><![CDATA[<h4>It might have happened to you in the past, not quite understanding which you should use</h4><figure><img alt="Element vs. HTMLElement vs. ReactElement: when should I use each?" src="https://cdn-images-1.medium.com/max/1024/0*APn_H3l9mvJJ_OYp" /><figcaption>Photo by <a href="https://unsplash.com/@amit_lahav?utm_source=medium&amp;utm_medium=referral">Amit Lahav</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>One of TypeScript’s great features is the level of specificity you can achieve when typing variables. You can define an array to be a collection of strings, or numbers, or a mix of them, but you can also establish that an element is either an HTMLInputElement or an HTMLSelectElement. However, the ease to designate the granularity of your variable types can lead to much confusion when you are starting out.</p><p>One of the fields where I have seen programmers being more inconsistent is when typing HTML elements, especially while working with React. To be fair, it’s a little disconcerting when you consider the vast range of possibilities you have, particularly when you are starting to work with TypeScript.</p><p>So, let’s try and demystify when to use each.</p><h3>Definitions</h3><p>First, let’s define each of these terms:</p><h4>Node type</h4><p>Node type is defined by TypeScript in <a href="https://github.com/microsoft/TypeScript/blob/master/lib/lib.dom.d.ts">this library definition</a>. This interface is a base ancestor for most DOM elements. Elements such as Select Options, DIVs, or HTML Forms inherit from Node<strong>.</strong></p><p>From the source code documentation:</p><blockquote>“Node is an interface from which a number of <strong>DOM</strong> API object types inherit. It allows those<strong> types to be treated similarly</strong>; for example, inheriting the same set of methods, or being tested in the same way.”</blockquote><p>Among other implementations found in Node, you will see nodeName (a read-only string), childNodes (a read-only a list of elements of type ChildNode), and many other commonly used properties and methods to manipulate nodes.</p><h4>Element type</h4><p>Element type inherits, among others, from Node type. This one gets defined in TypeScript’s standard DOM types set (you can <a href="https://github.com/microsoft/TypeScript/blob/master/lib/lib.dom.d.ts">check it out here</a>). According to the documentation in the source code:</p><blockquote>“Element is the most general <strong>base</strong> class from which all objects in a <strong>Document</strong> inherit.”</blockquote><p>The two highlights are my own, and I think they tell what this type is about: a base class for objects that will end up in the Document Object Model.</p><p>Next, the documentation for Element type source code states this:</p><blockquote>“It only has methods and properties common to all kinds of elements. More specific classes inherit from Element.”</blockquote><p>This is the most generic type you can have, second to the Node type. Other types will inherit from it. In here, you’ll find useful methods, such as getElementsByClassName method (which returns a collection of elements), or properties such as className (string).</p><h4>HTMLElement type</h4><p>This interface actually defines and inherits any element that will end up as an HTML tag. This excludes React’s custom tags. So, for instance, if you have a &lt;MainHeader /&gt; React component, it will not inherit from HTMLElement. <a href="https://www.typescriptlang.org/v2/docs/handbook/dom-manipulation.html">According to TypeScriptLang.org</a>, HTMLElement is “the backbone for DOM manipulation in TypeScript”.</p><p>Directly from TypeScript source code:</p><blockquote>“Any HTML element. Some elements directly implement this interface, while others implement it via an interface that inherits it.”</blockquote><p>HTMLElement will inherit directly from the Element type.</p><p>In the HTMLElement type, you’ll see common useful methods such as addEventListener or removeEventListener (obviously related to Events), offsetHeight property, and others.</p><p>HTML elements will inherit from this interface and extend with their own exclusive implementation. For instance, HTMLInputElement will extend from HTMLElement and create some properties and methods of their own, such as value, name, and placeholder. However, HTMLSelectElement implements properties that do not exist in HTMLInputElement, such as selectedIndex, or multiple.</p><p>By the way, these types can also override any of the properties or methods inherited, following of course a set of established rules, such as that the super property or method is not static, keeping the signature or the original method, etc.</p><h4>ReactElement type</h4><p>This one is defined in the @types/react package, which you can <a href="https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts">check out here</a>. ReactElement is also an interface. An important thing to note is that this is not an actual DOM element, nor does it inherit from TypeScript’s previously discussed types. React’s functional components return either a ReactElement or null.</p><p>A ReactElement type could be considered the primitive definition for other types, such as a<strong> </strong>JSX.Element or JSX.IntrinsicElements.</p><p>A ReactNode type can be a ReactElement, a string, a number, or even null, among other types. Incidentally, React’s class components render method return type is ReactNode.</p><p>On the other hand, a JSX.Element can also be a ReactElement; however, this one explicitly defines its<em> </em>type and props both as any, so this one is more generic and loose.</p><p>Its interface definition looks like this:</p><pre>interface <strong>ReactElement</strong><em>&lt;</em>P = any, T extends string | JSXElementConstructor<em>&lt;</em>any<em>&gt; </em>= string | JSXElementConstructor<em>&lt;</em>any<em>&gt;&gt; {<br>    </em><strong>type</strong>: T;<br>    <strong>props</strong>: P;<br>    <strong>key</strong>: Key | null;<br><em>}</em></pre><h3>Let’s See Some code</h3><p>Consider the following snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5db3eebeeea6376cf993d481d7973bbb/href">https://medium.com/media/5db3eebeeea6376cf993d481d7973bbb/href</a></iframe><p>Several things will become obvious here. First, when you call document.createElement, what you get back is TypeScript’s best guess of what you intend to create. So if you call document.createElement(‘div’), you’ll get an HTMLDivElement. If you tried to create an unknown tag, you’ll be getting back an HTMLUnknownElement.</p><p>This HTMLDivElement will inherit directly from HTMLElement, which in turn inherits straight from, among others, Element type. Finally, Element inherits the signature from Node.</p><p>This hierarchy of ancestry will provide us with the full scope of methods and properties passed down to our instance and is one of the basic features of polymorphism.</p><p>Not all elements that you can put in a page through the DOM have their specific element type in TypeScript. Consider the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58cc881ea916eca64544e320ffbcc5a3/href">https://medium.com/media/58cc881ea916eca64544e320ffbcc5a3/href</a></iframe><p>In this case the &lt;header&gt;&lt;/header&gt; element will bear a plain HTMLElement type. At least at this point in time, there is no HTMLHeaderElement. This header instance will receive every member inherited from Node and Element while also everything that comes with HTMLElement, which is its own type.</p><p>Note that, unless declared programmatically through TypeScript, some standard Document methods for querying the DOM will return a generic HTMLElement, even when they have a specific type defined in TypeScript<strong>.</strong> This could happen when, at runtime, there is no way, for example, for getElementById to know what kind of element it will find. Casting to what you actually know you are going to get is fine is these cases, for example:</p><pre>// casting the return value from getElementById<br>const div:HTMLDivElement = document.getElementById(&#39;div_id&#39;) <strong>as HTMLDivElement</strong>;</pre><p>Type-casting elements like this will be especially important for elements with exclusive properties or methods like HTMLSelectElement mentioned previously in this article.</p><h3>Let’s Check React Components Typing</h3><p>For React functional components, you are going to want to return the ReactElement, as such:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9975420bb8782963d93e34f0be9763ed/href">https://medium.com/media/9975420bb8782963d93e34f0be9763ed/href</a></iframe><p>Line 13 of the previous example states that this Appointment component will be returning a ReactElement.</p><p>Now, interestingly enough, React types work in a very similar way to how HTMLElements do on TypeScript. At the top of the pyramid, you will find the interface extending our previous example: React.FC. This one works exclusively for functional components, and it is the base for all React functional components.</p><p>React.FC has a brother, React.Component type. According to the source code, this is a “base component for plain JS classe.”</p><p>So this one you will be using for class components, like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/312b7efa79c41ca743e31098500d872f/href">https://medium.com/media/312b7efa79c41ca743e31098500d872f/href</a></iframe><p>Notice that the render function of a React Class component will return a React.ReactNode type.</p><p>Right after React.Component and React.FC interfaces, you’ll find a number of other interfaces, but three of them are particularly interesting to me. The first one is ReactElement. As stated above, this is the type that will be returned by React.FC, but more interestingly, ReactElement inherits directly into JSX.Element interface, which in turn, inherits to JSX.IntrinsicElements. This last one is very interesting since it defines the HTML that will be transpiled from JSX code (similar to what TypeScript does with HTMLElements, HTMLInputElement, and the like).</p><p>Here’s a screenshot of the source code for JSX.<strong>IntrinsicElements</strong> interface source code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F2NG4VL3P-rMMZ2x1oHr8Q.png" /><figcaption>JSX.IntrinsicElements defines HTML elements to be transpiled from JSX.</figcaption></figure><h3>Conclusion</h3><p>Normally, you should not fiddle too much with return types when creating your React components in TypeScript. However, there are some valid use cases, such as when your linter is set to specify a return type as opposed to being set to let the transpiler infer the type. See — noImplicitAny and strict: true settings in your tsconfig.ts.</p><p>As a rule of thumb, you should specify types in your code when the linter complains, which usually means that TypeScript’s engine can’t infer the variable type you are trying to use.</p><p>Ideally, you should understand what you are using. If anything, you owe it to yourself to learn and appreciate what you are implementing and if what you are using is the right tool for the task.</p><blockquote>“We see nothing until we understand it.” — John Constable, XIX century English painter</blockquote><p>Thanks for reading!</p><h3>Further Reading</h3><ul><li><a href="https://www.typescriptlang.org/docs/">TypeScript official documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cda21315ddd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/typescript-reactjs-the-element-vs-reactelement-vs-htmlelement-vs-node-confusion-6cda21315ddd">Element vs. ReactElement vs. HTMLElement vs. Node Confusion in TypeScript and React</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get Over Your Fear of Shining]]></title>
            <link>https://medium.com/@pablo.delvalle.cr/get-over-your-fear-of-shining-d6ada2738da7?source=rss-3114c92aac3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6ada2738da7</guid>
            <category><![CDATA[live]]></category>
            <category><![CDATA[shine]]></category>
            <category><![CDATA[overcome-fear]]></category>
            <category><![CDATA[happiness]]></category>
            <category><![CDATA[existentialism]]></category>
            <dc:creator><![CDATA[Pablo A. Del Valle H.]]></dc:creator>
            <pubDate>Mon, 08 Jun 2020 14:01:54 GMT</pubDate>
            <atom:updated>2020-06-08T14:01:54.417Z</atom:updated>
            <content:encoded><![CDATA[<h4>Have you ever revisit a moment in your day when you could have done something amazing, only to say ‘I wish I had the guts to do it’</h4><figure><img alt="Conquer your fears and shine, you won’t regret it." src="https://cdn-images-1.medium.com/max/1024/0*_1mK-ewGyQ4yI5Vo" /><figcaption>Photo by <a href="https://unsplash.com/@litallevy?utm_source=medium&amp;utm_medium=referral">Lital Levy</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When Mr. Harold Crick, a very uptight and conventional IRS agent finds himself falling in love with Miss Pascal, he keeps struggling to show her, using his own words, that “<em>I want you</em>”.</p><p>Ana Pascal, who is an upbeat and cheery baker, can’t quite figure it out, she is just waiting for Mr. Crick to show his true self, to break out of the mold… Maybe there is something there, but she doesn’t know, because he never had the chance, or rather, never decided to take the risk to liberate his true persona.</p><p><em>At this point, I should say that, if you haven’t watched Stranger Than Fiction movie, go watch it, then come back and continue reading from this point.</em></p><p>Then, one night, Mr. Crick, sick of always saying “no”, “not now”, “let’s do it another time”, decided that maybe he <em>can</em> do it, maybe if he takes a deep breath and opens up… He decides to <em>shine</em>.</p><p>We all have seen the scene, Will Ferrell’s character looking at the guitar. The hesitation in his eyes, we could all identify with what Mr. Crick was feeling and struggling with. Finally, he decided, closed his eyes, and let go. Took the guitar. Played a few verses of <em>Whole Wide World</em> by British band <em>Wreckless Eric</em>, which prompted Miss Pascal, phenomenally performed by Maggie Gyllenhaal, to jump and finally kiss him.</p><p><em>What happened?</em></p><p>Crippling shyness is a real thing. In fact, even regular outgoing and extrovert people have felt it in one time or another.</p><p>But you need to leave that behind because the prize to let go is larger than the safety of the status quo.</p><p>And, I think, the Stranger Than Fiction movie metaphor holds very true here. This is a man who, if he does everything that is expected of him, if he follows all the set rules and routes that he should take… he will be killed by the omniscient narrator (Emma Thompson’s character).</p><p>Is only when he transitions from taking the “<em>known road</em>” that things start to turn up for him. And at first, they may not look great, it might seem daunting.</p><p>I’ll argue that insisting on not opening up is actually more selfish than you think. Charles Darwin described shyness as a type of “<em>self-attention</em>”.</p><p><strong>You can’t shine when your inner-self is always thinking what others are thinking of you.</strong></p><p>Also, if you share your hobbies, what you like and dislike, your personality, your feelings you may find that there are more people feeling the same things that you are feeling now, they might even help you when you need to overcome your personal situation.</p><p>Have you ever felt anxious about “<em>what-ifs</em>” in your life? Wondered about a job, a person you like, a new skill that you always wanted to learn, the path not taken. Well… if you ask the question you might get the answer. If you try you might win.</p><p>So overcome, be bold, speak up. Shine.</p><blockquote>When I was a young boy<br>My mama said to me<br>“There’s only one girl in the world for you<br>And she probably lives in Tahiti.”</blockquote><blockquote>I’d go the whole wide world<br>Go the whole wide world just to find her</blockquote><blockquote>…</blockquote><blockquote>— Whole Wide World by Wreckless Eric</blockquote><p>Go, even if it’s the <em>whole wide world</em> away, find what you are looking for; you may find that you’ll enjoy more the journey.</p><h3>Thanks for reading!</h3><p>Find me on <a href="https://www.linkedin.com/in/pablo-del-valle">LinkedIn</a>, <a href="https://medium.com/@pablo.delvalle.cr">Medium</a>, <a href="https://github.com/delvalle">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6ada2738da7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[User-oriented web architecture: heal the relationship with your user first, the rest will follow]]></title>
            <link>https://uxdesign.cc/user-oriented-web-architecture-heal-the-relationship-with-your-user-first-the-rest-will-follow-3d4b65b98ae1?source=rss-3114c92aac3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d4b65b98ae1</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[user-experience]]></category>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[ux]]></category>
            <dc:creator><![CDATA[Pablo A. Del Valle H.]]></dc:creator>
            <pubDate>Wed, 03 Jun 2020 12:03:30 GMT</pubDate>
            <atom:updated>2020-06-05T23:32:15.398Z</atom:updated>
            <content:encoded><![CDATA[<h4>Whenever we forget about what the user really NEEDS and WANTS we could end up going down a rabbit hole of unnecessary decisions that affect our final product.</h4><figure><img alt="Consider the User first, then the Product" src="https://cdn-images-1.medium.com/max/1024/0*aT7u-HdW-QVV9BD4" /><figcaption>Photo by <a href="https://unsplash.com/@kellysikkema?utm_source=medium&amp;utm_medium=referral">Kelly Sikkema</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When <a href="https://twitter.com/aerotwist">Paul Lewis</a>, a lead developer for Google, <a href="https://www.youtube.com/watch?v=_yCz1TA0EL4">was benchmarking some of the most popular</a>, recently released, web frameworks and libraries he noticed that <strong>many of these were actually slowing down the user-experience</strong>, sometimes exponentially. At this point, he wondered why developers tend to install and use whatever just came out last week, without analyzing the metrics of these frameworks.</p><p>He then realized, after some interactions with many developers on Twitter, that these developers went “<em>library or framework happy</em>”, and picked up whatever was released that week because, in many cases according to his poll, it was <strong>trendy or fun</strong>.</p><p>And <em>it is</em> fun to play with the newest tools. He summarized his analysis of what developers told him as follows: “<em>having fun when writing code is more important to me than other factors</em>”.</p><p>This approach, as Paul Lewis puts it, focus on the “<em>developer ergonomics</em>”, instead of looking at what the <strong>user experience</strong> is and how it can be improved, in essence, the <strong>user needs</strong>.</p><h4>The “clean code obsession”</h4><p>Dan Abramov, <a href="https://overreacted.io/goodbye-clean-code/">blogged about this</a> in a post he titled “Goodbye, Clean Code”, in a different perspective: the developer within a team perspective. Sometimes we obsessed ourselves, as developers, in writing “<em>clean</em>” code. To the point that we might end up rewriting a large chunk of our codebase for the sake of “<em>cleanliness</em>” or “<em>properness</em>”.</p><blockquote>Am I saying that you should write “dirty” code? No. I suggest to think deeply about what you mean when you say “clean” or “dirty”. Do you get a feeling of revolt? Righteousness? Beauty? Elegance? How sure are you that you can name the concrete engineering outcomes corresponding to those qualities?</blockquote><blockquote>- Dan Abramov</blockquote><p>And what he is saying is actually really important. <strong>You are not coding for yourself, you are not the sole user of the product you want to put out there</strong> for the world to enjoy. And sometimes we, as developers, tend to think that our effort is an individual accomplishment and that the “<em>correctness</em>” of our code is the recognition we need to validate us as good programmers.</p><h4>We are not considering the correct factors</h4><p>In recent years, I came across a <strong>method for estimating</strong>, in a supposedly deterministic way, the outcome of events allegedly impossible to determine using other principles. This methodology heavily relies on a mathematical and statistical analysis of both previous and random sampling to obtain pure numerical probabilistic estimations. No surprise, this method is called the “<strong><em>Monte Carlo method</em></strong>” — yes, after the famous <em>Monte Carlo Casino</em> in Monaco.</p><p>Now, I will not dispute the value of properly analyzing a pattern, statistically aggregate the possible outcomes and define, in a formulaic way, the likely scenarios that the numbers generated. There is huge applicability in several fields such as climate, physics, stocks, even health.</p><p>However, <strong>this numbers-only approach can not be translated fully to human behavior science</strong>. At least not at its purest form. Human behavior is mostly empirical and, however many have tried, you can’t straitjacket how an individual will react to a single event based on many simulations.</p><h4>Behavior-Driven Development</h4><p>My suggestion is to bring in the user, consider his actual <em>needs,</em> and <em>wants</em>. Whenever we take business decisions, budget, scheduling, there is a legitimate usage of statistical analysis.</p><p>However, let me quote, out of the finance world, one of the phrases that I think applies to many life, and certainly business, situations:</p><blockquote>Past Performance Is No Guarantee of Future Results</blockquote><p><strong>Quantitative probabilistic</strong> should be paired with <strong>sensitivity analysis</strong>. I would argue that there is absolutely no reason why a project should start without a complete and profound study of the main target you want to bring into your product: <strong>the end-user</strong>.</p><p>The ability to bring confidence in a project is not defined merely by the numbers and sampling of dispersed simulations, but rather by getting to know who will end up consuming what you are going produce.</p><p>Let the user drive your development.</p><h4>Behavioral economics and the participation of the user</h4><p>This is not, by any means, a new science. In fact, in 2017 Richard Thaler received the Nobel Prize in the field of Economics for a study that established that:</p><blockquote>“… people are <strong>predictable irrational</strong> in ways that defy economic theory”</blockquote><blockquote>- Richard Thaler, Nobel Prize in the field of Economics</blockquote><p>So, while probabilistic models, mathematical algorithms, statistical analysis might help to understand what happened in a past event, or to simulate and estimate possible scenarios, you just can’t pigeon hole all your users in a spreadsheet. You are going to need to go to the field and see for yourself, use the product yourself, talk to the user, experience his feelings and interactions.</p><p>Paul Lewis finished his talk with this immense takeaway:</p><blockquote>If it takes me an extra week, but every single one of my users get a better experience, it was worth my time… You should always focus on the people bit.</blockquote><blockquote>- Paul Lewis, developer lead at Google</blockquote><p><strong>Data </strong>(or money for what it&#39;s worth) <strong>should be a factor when you define a decision, but not the ultimate determinant.</strong></p><p>And, by the way, when <em>Richard Thaler</em> was asked how he would spend his Nobel Prize money he ‘jokingly’ responded: I intend to spend it as “<em>irrationally as possible</em>”.</p><p>Further reading:</p><ul><li><a href="https://developers.google.com/web/tools/lighthouse">Google’s Lighthouse tool</a> to benchmark the performance of websites on Chrome browser</li></ul><p>Thanks for reading!</p><p>Find me on <a href="https://www.linkedin.com/in/pablo-del-valle">LinkedIn</a>, <a href="https://medium.com/@pablo.delvalle.cr">Medium</a>, <a href="https://github.com/delvalle">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d4b65b98ae1" width="1" height="1" alt=""><hr><p><a href="https://uxdesign.cc/user-oriented-web-architecture-heal-the-relationship-with-your-user-first-the-rest-will-follow-3d4b65b98ae1">User-oriented web architecture: heal the relationship with your user first, the rest will follow</a> was originally published in <a href="https://uxdesign.cc/">UX Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GraphQL ORM with TypeScript implementing Apollo Server(Express) and SQLite]]></title>
            <link>https://medium.com/swlh/graphql-orm-with-typescript-implementing-apollo-server-express-and-sqlite-5f16a92968d0?source=rss-3114c92aac3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f16a92968d0</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[sqlite]]></category>
            <category><![CDATA[orm]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[apollo-server]]></category>
            <dc:creator><![CDATA[Pablo A. Del Valle H.]]></dc:creator>
            <pubDate>Wed, 03 Jun 2020 05:25:20 GMT</pubDate>
            <atom:updated>2020-06-10T04:35:21.188Z</atom:updated>
            <content:encoded><![CDATA[<h4>Simple step by step of how to create a basic GraphQL end-point with TypeScript and Apollo Server with SQLite as a database</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bVUhPe6NOx_ig3QV" /><figcaption>Photo by <a href="https://unsplash.com/@djjabbua?utm_source=medium&amp;utm_medium=referral">David Torres</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>I’ve created another article on GraphQL with Python 🐍 if you want to check it out, </em><a href="https://medium.com/@pablo.delvalle.cr/python-flask-with-graphql-server-with-sqlalchemy-and-graphene-and-sqlite-ac9fcc9d3d83"><em>click here</em></a><em>.</em></p><p><strong>TypeScript and GraphQL are a match made in heaven</strong>. They just are. In this article, I’ll try to show you why by creating a simple <strong>GraphQL</strong> application end-point using <strong>Apollo Server</strong> and <strong>SQLite</strong> as a database, however, you can extrapolate the knowledge and use it for any other organized collection of data, and the reason why that can happen is that we will also implement Object-Relational Mapping, with <a href="https://typeorm.io/"><strong>TypeORM</strong></a>.</p><figure><img alt="GraphQL" src="https://cdn-images-1.medium.com/max/200/1*-qBiNyBHouv85UkiZOvdSg.png" /><figcaption>GraphQL</figcaption></figure><p><strong>TypeORM</strong> supports <strong>Active Record</strong> and <strong>Data Mapper</strong> architecture patterns. Active Record is arguably simpler, so we will use that one for our sample application.</p><p><strong>Apollo Server</strong> provides a robust framework to serve our data. It’s easy to set up, highly compatible with all major data sources, and also implements a graphical interface for development purposes that we will use later in this article.</p><p>So, what would be the best way to go? Let’s go <strong>Pokémon</strong>!</p><h4>Project Setup and Structure 🚜</h4><figure><img alt="TypeScript" src="https://cdn-images-1.medium.com/max/200/1*tkNlkRnfu8DzXdeQN6CJag.png" /><figcaption>We’ll use TypeScript strong typing.</figcaption></figure><p>We will create a <strong>sample end-point to query a Pokémon collection</strong> stored in an SQLite database.</p><p>You will be able to <strong>search</strong> by name and receive a node with the requested information, such as <em>name</em>, <em>type</em>, <em>abilities</em>. Also, you can <strong>create</strong> new entries using GraphQL’s mutations.</p><p>First, we will install a few foundational packages through <strong>npm</strong> (or <em>yarn</em> if that’s your cup of tea).</p><pre><strong>npm i -SD </strong>ts-node-dev</pre><pre><strong>npm i -S</strong> @types/node apollo-server-express express graphql reflect-metadata sqlite3 type-graphql typeorm typescript</pre><p>In our root we’ll need a <strong>tsconfig.json</strong> file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc5e047120c7287ed6bb47a8895a75b1/href">https://medium.com/media/dc5e047120c7287ed6bb47a8895a75b1/href</a></iframe><p>You’ll notice that we defined a source directory in “<strong>/src/</strong>”.</p><h4>Database Models 🗄</h4><p>Three Models will be created in the “<strong>/src/models/</strong>” directory: <strong>Abilities.ts</strong>, <strong>Pokemon.ts</strong>, <strong>Types.ts</strong>, and<strong> PokemonAbilities.ts</strong>. Each of these will become a table in the SQLite database. There is going to be a barrel file too (<strong>index.ts</strong>).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd4f69a57af1e53d6a25ec908bb699ea/href">https://medium.com/media/cd4f69a57af1e53d6a25ec908bb699ea/href</a></iframe><p>Apart from the <strong>TypeORM</strong> decorators, we are adding <strong>type-graphql</strong> decorators to prepare these same Models as GraphQL types.</p><h4>Database seed 🌱</h4><figure><img alt="SQLite" src="https://cdn-images-1.medium.com/max/200/1*I0MVnFr06PZj79DB-ydyXA.png" /><figcaption>SQLite 3 for a database.</figcaption></figure><p>Our database is going to have a few rows on load, for that we will create an <strong>init_db.ts</strong> script inside “<em>/src/database/</em>”. We’ll call the method in this file once the application starts up. This means that every time you run the start command, your database will be wiped out. This is, of course, due to this being a simple demo, for a more permanent arrangement, you will only run this file once.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a0e48bafea15ceb8b9d6bd3cb0e51d4/href">https://medium.com/media/3a0e48bafea15ceb8b9d6bd3cb0e51d4/href</a></iframe><p>Now, if you are wondering how our application knows where to pick up the Models or where to store our database, that’s because we are creating a “<em>guide</em>” file for <strong>TypeORM</strong>, this file will be located at the root of our app, and it needs to be called <strong>ormconfig.json</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83eefda976d6ca11f9aec829fc88de24/href">https://medium.com/media/83eefda976d6ca11f9aec829fc88de24/href</a></iframe><p>At this point, we have created our <strong>Models</strong> and seeded our database, so now we are going to need to work on our GraphQL <strong>Schema</strong>.</p><h4>GraphQL Schema 📐</h4><p>The <strong>Resolvers.ts</strong> file under “<em>/src/schema/</em>” directory will expose the resolvers for the <strong>queries</strong> and <strong>mutations</strong>. In our case, we will have 6 queries and 1 mutation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1bb34abcf4bd7088066093841ccf59b/href">https://medium.com/media/f1bb34abcf4bd7088066093841ccf59b/href</a></iframe><h4>Using Apollo Server-Express to expose our GraphQL end-point 🌏</h4><figure><img alt="Apollo Server" src="https://cdn-images-1.medium.com/max/200/1*G8dAY_VoveZ1G7rDKuPRPA.png" /><figcaption>Apollo Server</figcaption></figure><p>Finally, we are at the last step of our application development. We are going to wire up <strong>Apollo Server-Express</strong> with our GraphQL end-point.</p><p>For this, we are going to create an entry point for our app. In our case, let’s call it <strong>server.ts</strong> and leave it at the root of our project. Basically, it’s just a “<strong><em>main()</em></strong>” method that will be called right away at runtime.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a445aace25ffd9d19154e934130a91a2/href">https://medium.com/media/a445aace25ffd9d19154e934130a91a2/href</a></iframe><p>This “<em>main()</em>” method will first deploy our database by calling “<strong>init_db()</strong>” on line 10 and then deploying express server with Apollo on line 20.</p><p>On the <strong>package.json</strong> add this script:</p><pre><em>“watch”: “ts-node-dev -respawn -transpileOnly ‘src/server.ts’”</em></pre><p>If you run the previous command as `<strong><em>npm run watch</em></strong>`, you can navigate to the GraphQL graphical interface, which will be on localhost, port 4000. A simple query you can run is allPokemon which will return the full list of Pokémon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*taJtY1wwWwqX6OPdh2tdPw.png" /></figure><p>A rather more complex query you can try is getPokemonAbilities which will receive a “<em>name</em>” parameter and, in turn, you will get back two result sets, the first is the Pokémon searched and the second will be a list of abilities associated with him. This is done <strong>with the help of a UNION</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F3AnMidXr_RkDpjdOlWEsw.png" /></figure><h4>Mutating data 🐛</h4><p>Lastly, we can create more rows in our database. For the sake of brevity, we will only add a new entry with its name. You can easily expand this to add more columns and relationships.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iVtTPIif5TDZYKWspE-zow.png" /></figure><p>It will return the created item.</p><p>Probably, a good place to go from here will be <a href="https://github.com/typestack/class-validator">class-validator</a>, which will allow you to validate your class properties using decorators.</p><p>Also, you can expand on <a href="https://graphql.org/learn/authorization/">GraphQL Authorization</a> which is going to add another layer of permissions and security to your end-points.</p><h3>What’s Next and Further Reading</h3><p>More subjects that you can explore:</p><ul><li><a href="https://medium.com/@pablo.delvalle.cr/typescript-reactjs-the-element-vs-reactelement-vs-htmlelement-vs-node-confusion-6cda21315ddd">TypeScript / ReactJS: The Element vs. ReactElement vs. HTMLElement vs. Node confusion</a></li><li><a href="https://medium.com/swlh/soap-restful-graphql-selecting-the-right-communication-standard-997ff43252cd">SOAP, RESTful, GraphQL: selecting the right communication standard</a></li><li><a href="https://medium.com/swlh/dockerize-your-next-js-application-91ade32baa6">Dockerize your Next.JS application</a></li><li><a href="https://medium.com/swlh/is-behavior-driven-development-right-for-your-project-462e9371516d">Is Behavior-Driven Development right for your Project?</a></li></ul><p>Further reading:</p><ul><li><a href="https://graphql.org/learn/">GraphQL official documentation</a></li><li><a href="https://www.typescriptlang.org/docs/">TypeScript official documentation</a></li><li><a href="https://www.apollographql.com/docs/apollo-server/">Apollo Server official documentation</a></li><li><a href="https://www.sqlite.org/docs.html">SQLite official documentation</a></li></ul><h3>Thanks for reading!</h3><p>Find me on <a href="https://www.linkedin.com/in/pablo-del-valle">LinkedIn</a>, <a href="https://medium.com/@pablo.delvalle.cr">Medium</a>, <a href="https://github.com/delvalle">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f16a92968d0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/graphql-orm-with-typescript-implementing-apollo-server-express-and-sqlite-5f16a92968d0">GraphQL ORM with TypeScript implementing Apollo Server(Express) and SQLite</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>