<?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 Hari Narasimhan on Medium]]></title>
        <description><![CDATA[Stories by Hari Narasimhan on Medium]]></description>
        <link>https://medium.com/@harin76?source=rss-f86d8caa0c3b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GNG9hOVxbrdtqgSAiSihiw.jpeg</url>
            <title>Stories by Hari Narasimhan on Medium</title>
            <link>https://medium.com/@harin76?source=rss-f86d8caa0c3b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 15:58:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@harin76/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[Generating solid.js components from JSON]]></title>
            <link>https://harin76.medium.com/generating-solid-js-components-from-json-7cc5ef37c7f4?source=rss-f86d8caa0c3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cc5ef37c7f4</guid>
            <category><![CDATA[hyperscript]]></category>
            <category><![CDATA[solidjs]]></category>
            <dc:creator><![CDATA[Hari Narasimhan]]></dc:creator>
            <pubDate>Sun, 17 Oct 2021 07:39:22 GMT</pubDate>
            <atom:updated>2021-10-17T07:39:22.671Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*49wvzIlWcxnisJ6q4SU06Q.png" /></figure><p>SolidJS is a new UI framework that combines the best practices of many contemporary frameworks such as React, Svelte, Vue, etc. It resembles ReactJS, but its inner workings are different. SolidJS achieves vanilla js performance levels through its compilers and deeper optimizations.</p><p>Solid provides JSX support and pre-compiles all templates into optimized functions at build time. While the suggested approach to building components in SolidJS is to use the JSX and pre-compile, there are times when we need some dynamic rendering.</p><p>I have used dynamic rendering in many projects where I had to render a page from a JSON structure. I wanted to check if support for such a rendering exists in SolidJS. Well, SolidJS provides HyperScript support to achieve dynamic rendering from a JSON structure.</p><p>Here is an example of how to use it. You can copy-paste this in the <a href="https://playground.solidjs.com/">solid playground</a> and try it out. Please note that HyperScript rendering is discouraged by the SolidJS team and should be used only when the requirement absolutely demands it. The approach uses a recursive function, HyperScript function, and HyperDOM to render a dynamic component.</p><pre>import { render } from &quot;solid-js/web&quot;;<br>import h from &quot;solid-js/h&quot;;</pre><pre>function isArray (val) {<br>  return Array.isArray(val)<br>}</pre><pre>function isEmpty(val){<br>  return  val === undefined ||<br>          val === null ||<br>          (typeof val === &quot;object&quot; &amp;&amp; Object.keys(val).length === 0) ||<br>          (typeof val === &quot;string&quot; &amp;&amp; val.trim().length === 0)<br>}</pre><pre>function isString(val) {<br>  return typeof val === &#39;string&#39;<br>}</pre><pre>// Lazy clone deep implementation<br>function cloneDeep(val) {<br>  if (typeof val === &#39;object&#39;) {<br>    const str = JSON.stringify(val)<br>    return JSON.parse(str)<br>  }<br>  return val<br>}</pre><pre>function createComponent(dNode, h) {<br>  // Handle empty elements and return empty array in case the dNode passed in is empty<br>  if (isEmpty(dNode)) {<br>    return [];<br>  }<br>  // if the el is array call createComponent for all nodes<br>  if (isArray(dNode)) {<br>    return dNode.map((child) =&gt; createComponent(child, h))<br>  }<br>  let children = []; <br>  <br>  // If the node has children render them too<br>  if (dNode.children &amp;&amp; dNode.children.length &gt; 0) {<br>    dNode.children.forEach((c) =&gt; {<br>      if (isString(c)) {<br>        children.push(c)<br>      } else {<br>        children.push(createComponent(c, h))<br>      }<br>    });<br>  }<br>// Need to clone <br>  const properties = cloneDeep(dNode.properties) || {}<br>  <br>  // This is to satisfy React warning that children should have a key<br>  properties.key = Date.now() +  &#39;.&#39; + (Math.random() * 1000)<br>  console.log(dNode.tagName, properties)<br>  return h(dNode.tagName, properties, children.length &gt; 0? children : dNode.textNode)<br>}</pre><pre>const nodes = {<br>  tagName: &#39;div&#39;,<br>  children: [<br>    {<br>      tagName: &#39;h1&#39;,<br>      textNode: &#39;Great News&#39;,<br>      properties: {<br>        style: {&#39;text-transform&#39;: &#39;uppercase&#39;}<br>      }<br>    },<br>    {<br>      tagName: &#39;h3&#39;,<br>      textNode: &#39;YOU CAN CREATE SOLID COMPONENTS OUT OF JSON&#39;,<br>      properties: {<br>        style: {&#39;text-transform&#39;: &#39;lowercase&#39;}<br>      }<br>    },<br>    {<br>      tagName: &#39;img&#39;,<br>      properties: {<br>        src: &#39;<a href="https://www.solidjs.com/assets/logo.123b04bc.svg&#39;">https://www.solidjs.com/assets/logo.123b04bc.svg&#39;</a>,<br>        width: &#39;100px&#39;,<br>        height: &#39;100px&#39;<br>      }<br>    },<br>    {<br>      tagName: &#39;hr&#39;<br>    },<br>    {<br>      tagName: &#39;a&#39;,<br>      properties: {<br>        href: &#39;#&#39;<br>      },<br>      textNode: &#39;solid.js&#39;<br>    }<br>  ]<br>}</pre><pre>function UIEngine (props) {<br>  return createComponent(props.nodes, h)<br>}</pre><pre>render(() =&gt; &lt;UIEngine nodes={nodes}/&gt;, document.getElementById(&quot;app&quot;));</pre><p>Similar Stories</p><ul><li><a href="https://harin76.medium.com/generate-vue-js-components-from-a-json-javascript-dom-structure-a76534478d15">Generate Vue.js components from a JSON / JavaScript DOM Structure</a></li><li><a href="https://javascript.plainenglish.io/generating-react-components-from-json-850d25a5cd67">Generating React Components from JSON</a></li></ul><p>References</p><ul><li><a href="https://www.solidjs.com/guide#no-compilation%3F">SolidJS</a></li><li><a href="https://www.solidjs.com/examples/simpletodoshyperscript">SolidJS</a></li><li><a href="https://github.com/ryansolid/dom-expressions/tree/main/packages/hyper-dom-expressions">dom-expressions/packages/hyper-dom-expressions at main · ryansolid/dom-expressions</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cc5ef37c7f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generating React Components from JSON]]></title>
            <link>https://javascript.plainenglish.io/generating-react-components-from-json-850d25a5cd67?source=rss-f86d8caa0c3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/850d25a5cd67</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Hari Narasimhan]]></dc:creator>
            <pubDate>Wed, 17 Feb 2021 03:45:06 GMT</pubDate>
            <atom:updated>2021-02-17T12:47:06.854Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KeUbwJ-6gLdt_oC0CAEKNA.png" /><figcaption>JSON to UI with React</figcaption></figure><p>In 2017, I wrote an <a href="https://harin76.medium.com/generate-vue-js-components-from-a-json-javascript-dom-structure-a76534478d15">article</a> that demonstrated generating a user interface from JSON or a Javascript object representation. I presented the concept in VueJs (2.x). At the core of the solution is a recursive function that takes a set of nodes and produces HTML components. This idea is useful for implementing tools such as content management systems. I did use the concept to hydrate custom pages for a no-code platform.</p><p>I love VueJs there is a bit of elegance in it. ReactJs is another remarkable framework. ReactJs has a very similar architecture (DOM diffing and patching) to VueJs. Both these frameworks have significant contributions in the area of browser-based frontend development.</p><p>I wanted to catch up with the ReactJs world. The best way to do it is to take it for a spin. I desired to re-write my original VueJs article in ReactJs. To my pleasant surprise, it ended up being easy.</p><p>Here is the JSON user interface definition that we will render.</p><pre>{<br>  &quot;tagName&quot;: &quot;div&quot;,<br>  &quot;children&quot;: [<br>    {<br>      &quot;tagName&quot;: &quot;h1&quot;,<br>      &quot;textNode&quot;: &quot;Great News&quot;,<br>      &quot;properties&quot;: {<br>        &quot;style&quot;: {<br>          &quot;textTransform&quot;: &quot;uppercase&quot;<br>        }<br>      }<br>    },<br>    {<br>      &quot;tagName&quot;: &quot;h3&quot;,<br>      &quot;textNode&quot;: &quot;YOU CAN CREATE REACT COMPONENTS OUT OF JSON&quot;,<br>      &quot;properties&quot;: {<br>        &quot;style&quot;: {<br>          &quot;textTransform&quot;: &quot;lowercase&quot;<br>        }<br>      }<br>    },<br>    {<br>      &quot;tagName&quot;: &quot;img&quot;,<br>      &quot;properties&quot;: {<br>        &quot;src&quot;: &quot;data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9Ii0xMS41IC0xMC4yMzE3NCAyMyAyMC40NjM0OCI+CiAgPHRpdGxlPlJlYWN0IExvZ288L3RpdGxlPgogIDxjaXJjbGUgY3g9IjAiIGN5PSIwIiByPSIyLjA1IiBmaWxsPSIjNjFkYWZiIi8+CiAgPGcgc3Ryb2tlPSIjNjFkYWZiIiBzdHJva2Utd2lkdGg9IjEiIGZpbGw9Im5vbmUiPgogICAgPGVsbGlwc2Ugcng9IjExIiByeT0iNC4yIi8+CiAgICA8ZWxsaXBzZSByeD0iMTEiIHJ5PSI0LjIiIHRyYW5zZm9ybT0icm90YXRlKDYwKSIvPgogICAgPGVsbGlwc2Ugcng9IjExIiByeT0iNC4yIiB0cmFuc2Zvcm09InJvdGF0ZSgxMjApIi8+CiAgPC9nPgo8L3N2Zz4K&quot;,<br>        &quot;width&quot;: &quot;100px&quot;,<br>        &quot;height&quot;: &quot;100px&quot;<br>      }<br>    },<br>    {<br>      &quot;tagName&quot;: &quot;hr&quot;<br>    },<br>    {<br>      &quot;tagName&quot;: &quot;a&quot;,<br>      &quot;properties&quot;: {<br>        &quot;href&quot;: &quot;#&quot;<br>      },<br>      &quot;textNode&quot;: &quot;react.js&quot;<br>    }<br>  ]<br>}</pre><p><strong>The recursive function</strong></p><p>In the VueJs example, the ‘createComponent’ function took two parameters</p><ol><li>A set of nodes</li><li>A rendering function</li></ol><p>There were no changes to the function. In the ReactJs implementation, we passed the reference to <a href="https://reactjs.org/docs/react-api.html#createelement">React.createElement</a> as the second parameter. I tweaked a little to satisfy React requirement that child elements should have a unique key. Here is the modified ‘createComponent’ implementation.</p><pre>// A helper to recursively create DOM nodes<br>// first argument is a set of nodes<br>// Second argument is a render function<br>function createComponent(dNode, h) {<br>  // Handle empty elements and return empty array in case the dNode passed in is empty<br>  if (_.isEmpty(dNode)) {<br>    return [];<br>  }<br>  // if the el is array call createComponent for all nodes<br>  if (_.isArray(dNode)) {<br>    return dNode.map((child) =&gt; createComponent(child, h))<br>  }<br>  let children = []; <br>  <br>  // If the node has children render them too<br>  if (dNode.children &amp;&amp; dNode.children.length &gt; 0) {<br>    dNode.children.forEach((c) =&gt; {<br>      if (_.isString(c)) {<br>        children.push(c)<br>      } else {<br>        children.push(createComponent(c, h))<br>      }<br>    });<br>  }</pre><pre>  // Need to clone <br>  const properties = _.cloneDeep(dNode.properties) || {}<br>  <br>  // To satisfy React warning that children should have a key<br>  properties.key = Date.now() +  &#39;.&#39; + Math.random(1000)<br>  return h(<br>    dNode.tagName,<br>    properties, <br>    children.length &gt; 0? children : dNode.textNode<br>  )<br>}</pre><p>The react implementation was straightforward. The functional component ‘UIEngine’ returns a component created using <a href="https://reactjs.org/docs/react-api.html#createelement">React.createElement</a>. The ‘UIEngine’ accepts a Javascript object or an array as a property. It uses the mostly unchanged ‘createComponent’ function from the VueJs example.</p><pre>function UIEngine({nodes}) {<br>   // The second parameter to the createComponent is <br>   // the React.createElement<br>   return createComponent(nodes, React.createElement)<br>}</pre><p>The ‘UIEngine’ is a regular react component and it can be rendered in JSX, as demonstrated in the complete example.</p><pre>       return (<br>          &lt;div&gt;<br>            &lt;UIEngine nodes={nodes} /&gt;<br>          &lt;/div&gt;<br>        )</pre><p>Here is the ‘<a href="https://jsbin.com/fezofa/edit?html,output">jsbin</a>’ link to the code.</p><p><strong>Full code for your reference</strong></p><pre>&lt;!DOCTYPE html&gt;<br>  &lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Document&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>    &lt;script src=&quot;<a href="https://cdn.jsdelivr.net/lodash/4/lodash.min.js">https://cdn.jsdelivr.net/lodash/4/lodash.min.js</a>&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;<a href="https://unpkg.com/react@16.12.0/umd/react.development.js">https://unpkg.com/react@16.12.0/umd/react.development.js</a>&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;<a href="https://unpkg.com/react-dom@16.12.0/umd/react-dom.development.js">https://unpkg.com/react-dom@16.12.0/umd/react-dom.development.js</a>&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;<a href="https://unpkg.com/@babel/standalone@7.8.3/babel.js">https://unpkg.com/@babel/standalone@7.8.3/babel.js</a>&quot;&gt;&lt;/script&gt;<br>    &lt;script type=&quot;text/babel&quot;&gt;<br>      <br>// A helper to recursively create DOM nodes<br>// first argument is a set of nodes<br>// Second argument is a render function<br>function createComponent(dNode, h) {<br>  // Handle empty elements and return empty array in case the dNode passed in is empty<br>  if (_.isEmpty(dNode)) {<br>    return [];<br>  }<br>  // if the el is array call createComponent for all nodes<br>  if (_.isArray(dNode)) {<br>    return dNode.map((child) =&gt; createComponent(child, h))<br>  }<br>  let children = []; <br>  <br>  // If the node has children render them too<br>  if (dNode.children &amp;&amp; dNode.children.length &gt; 0) {<br>    dNode.children.forEach((c) =&gt; {<br>      if (_.isString(c)) {<br>        children.push(c)<br>      } else {<br>        children.push(createComponent(c, h))<br>      }<br>    });<br>  }</pre><pre>// Need to clone <br>  const properties = _.cloneDeep(dNode.properties) || {}<br>  <br>  // This is to satisfy React warning that children should have a key<br>  properties.key = Date.now() +  &#39;.&#39; + Math.random(1000)<br>  return h(dNode.tagName, properties, children.length &gt; 0? children : dNode.textNode)<br>}      <br>      <br>      // The UI Engine component, takes a Javascript object/array or nodes as prop and renders it<br>      function UIEngine({nodes}) {<br>        return createComponent(nodes, React.createElement)<br>      }<br>      <br>      // An application component consuming the UiEngine<br>      function App() {<br>        const nodes = {<br>          tagName: &#39;div&#39;,<br>          children: [<br>            {<br>              tagName: &#39;h1&#39;,<br>              textNode: &#39;Great News&#39;,<br>              properties: {<br>                style: {&#39;textTransform&#39;: &#39;uppercase&#39;}<br>              }<br>            },<br>            {<br>              tagName: &#39;h3&#39;,<br>              textNode: &#39;YOU CAN CREATE REACT COMPONENTS OUT OF JSON&#39;,<br>              properties: {<br>                style: {textTransform: &#39;lowercase&#39;}<br>              }<br>            },<br>            {<br>              tagName: &#39;img&#39;,<br>              properties: {<br>                src: &#39;data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9Ii0xMS41IC0xMC4yMzE3NCAyMyAyMC40NjM0OCI+CiAgPHRpdGxlPlJlYWN0IExvZ288L3RpdGxlPgogIDxjaXJjbGUgY3g9IjAiIGN5PSIwIiByPSIyLjA1IiBmaWxsPSIjNjFkYWZiIi8+CiAgPGcgc3Ryb2tlPSIjNjFkYWZiIiBzdHJva2Utd2lkdGg9IjEiIGZpbGw9Im5vbmUiPgogICAgPGVsbGlwc2Ugcng9IjExIiByeT0iNC4yIi8+CiAgICA8ZWxsaXBzZSByeD0iMTEiIHJ5PSI0LjIiIHRyYW5zZm9ybT0icm90YXRlKDYwKSIvPgogICAgPGVsbGlwc2Ugcng9IjExIiByeT0iNC4yIiB0cmFuc2Zvcm09InJvdGF0ZSgxMjApIi8+CiAgPC9nPgo8L3N2Zz4K&#39;,<br>                width: &#39;100px&#39;,<br>                height: &#39;100px&#39;<br>              }<br>            },<br>            {<br>              tagName: &#39;hr&#39;<br>            },<br>            {<br>              tagName: &#39;a&#39;,<br>              properties: {<br>                href: &#39;#&#39;<br>              },<br>              textNode: &#39;react.js&#39;<br>            }<br>          ]<br>        };<br>        return (<br>          &lt;div&gt;<br>            &lt;UIEngine nodes={nodes} /&gt;<br>          &lt;/div&gt;<br>        )<br>      }</pre><pre>ReactDOM.render(&lt;App /&gt;, document.getElementById(&#39;root&#39;))<br>    &lt;/script&gt;<br>  &lt;/body&gt;<br>  &lt;/html&gt;</pre><p>This article shows how similar the VueJs and ReactJs framework are in their inner workings. Without changing even one line of the custom recursive rendering function, we created a component that can render a UI from JSON/Javascript object in ReactJS. It also demonstrates how to re-hydrate a UI component stored in JSON. Let me know what you think about this article. If you liked this article, please share.</p><p><strong>References</strong></p><p><a href="https://harin76.medium.com/generate-vue-js-components-from-a-json-javascript-dom-structure-a76534478d15">Generate Vue.js components from a JSON / JavaScript DOM Structure</a></p><p>React createElement — <a href="https://reactjs.org/docs/react-api.html#createelement">https://reactjs.org/docs/react-api.html#createelement</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=850d25a5cd67" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/generating-react-components-from-json-850d25a5cd67">Generating React Components from JSON</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Node.js Performance]]></title>
            <link>https://javascript.plainenglish.io/understanding-nodejs-performance-dc9f2673455e?source=rss-f86d8caa0c3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc9f2673455e</guid>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Hari Narasimhan]]></dc:creator>
            <pubDate>Sun, 14 Feb 2021 23:56:17 GMT</pubDate>
            <atom:updated>2021-02-15T07:05:43.483Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NqEsteabAso1K1UlToaGDg.jpeg" /><figcaption>GSLV-F08 liftoff © <a href="https://www.isro.gov.in/">https://www.isro.gov.in/</a></figcaption></figure><p>Many developers and architects jump into NodeJS after hearing stories of incredible speeds and its asynchronous IO. Most of them do not have a clear understanding of how NodeJS works. Understanding how the event loop works significantly helps in producing better NodeJS solutions.</p><p>I am not going to deep dive into the event loop. A simple search should provide abundant resources. For our discussion, let us assume that the event loop is responsible for handling async I/O in NodeJS. The event loop makes the single-threaded NodeJS runtime handle concurrency.</p><p>For the rest of this article, we will take a simple HTTP service and analyze the effect of callback processing time and blocking code on the response handling capacity of NodeJS runtime.</p><h4><strong>Blocking Code</strong></h4><p>By definition, any code that prevents the event loop from picking the next item in its queue is a blocking code. An example of a blocking code is a large for or a while statement.</p><h4><strong>A Simple HTTP Server</strong></h4><p>The magical three-line HTTP server. Isn’t it beautiful?</p><pre>const http = require(‘http’)</pre><pre>http.createServer((req, res) =&gt; {<br>    res.writeHead(200)<br>    res.end(‘Hello, World!’)<br>}).listen(8888)</pre><p>We are going to use autocannon. Let us install it globally</p><pre>npm i -g autocannon</pre><p>Testing the server for its base performance, let us use 100 connections and the default 10-second duration to generate traffic.</p><p>In my machine, this is the result obtained.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*x_JNgjyX6yv2s7Qj3qNPuw.png" /></figure><h4><strong>HTTP server with asynchronous callback</strong></h4><pre>const http = require(&#39;http&#39;)<br>const getResponse = async () =&gt; {<br>    return new Promise((resolve, reject) =&gt; {<br>        setTimeout(() =&gt; {<br>            return resolve(&#39;Hello, world!&#39;)<br>        }, 10) // Simulate a 10 ms delay for the data fetch<br>    })<br>}</pre><pre>// Our server is using the get response to fetch the &#39;Hello, World!&#39; string. This is to simulate a DB request</pre><pre>http.createServer(async (req, res) =&gt; {<br>    const result = await getResponse()<br>    res.writeHead(200)<br>    res.end(result)<br>}).listen(8888)</pre><p>Let us simulate a likely use case, like fetching data from the database. For this test, let us keep the response duration to 10 milliseconds. The result for this iteration is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*oolYRe-wihdVa8auCHw1tA.png" /><figcaption>At 10 ms per request</figcaption></figure><p>Let us repeat the test for 50, 100, 500, and 1000 ms delays.</p><p>Here are the results.</p><p><strong>At 50 ms</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*i0dPVw-xA33kaRBF-WFRGg.png" /><figcaption>At 50 ms per request</figcaption></figure><p><strong>At 100 ms</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*nFPKzHZ8Mn0SEBzZMeb7dQ.png" /><figcaption>At 100 ms per request</figcaption></figure><p><strong>At 500 ms</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*Sv9qLspYfuaBkVoJ3K4rcw.png" /></figure><p><strong>At 1000 ms</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*SBvvNSt-fEiOa4EQJ_1VXw.png" /></figure><h4><strong>Blocking the event loop — the cardinal sin</strong></h4><p>Let us tweak the first example. We will introduce a sleep function. To my knowledge, there is no native sleep. Our sleep function blocks the event loop, perfect for this demonstration.</p><pre>const http = require(&#39;http&#39;)</pre><pre>const sleep = (delayInMs) =&gt; {<br>  const start = Date.now()<br>  while (true) {<br>    if (Date.now() - start &gt;= delayInMs) {<br>      break;<br>    }<br>  }<br>}</pre><pre>http.createServer(async (req, res) =&gt; {<br>  // Sleep for 500 ms<br>  sleep(500)<br>  res.writeHead(200)<br>  res.end(&#39;Hello, world!&#39;)<br>}).listen(8888)</pre><p>The result is here, and it is dismal! Just look at the request per second and errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*TUvRx7yaR3_dXDT4bhNsgw.png" /></figure><h4><strong>Observations</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*odlmGpI0pszJ5gC1yvejqQ.png" /><figcaption>Latency with request callback time — Y-Axis Latency in ms</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*RLbzhaC7MHsACOnDG041yg.png" /><figcaption>Request per second with request callback time — Y-Axis RPS</figcaption></figure><p>The charts very clearly show that lower callback response time improves performance significantly.</p><h3><strong>Lessons</strong></h3><h4><strong>Lower your request processing time.</strong></h4><p>A low processing time significantly improves performance. Ideally, try to keep it under 10 ms. If that is not possible see strive to keep it as low as possible. There is a direct correlation to request processing time and the number of servers required. Lower request processing time has significant cost-saving benefits.</p><h4><strong>Never block the event loop.</strong></h4><p>As we saw, blocking the event loop even for something like 500 ms was disastrous. Background all your blocking calls to queues and workers.</p><h4><strong>Tools</strong></h4><p>Use the following tools to understand your NodeJS code and to tune it</p><ol><li>Autocannon — <a href="https://github.com/mcollina/autocannon">https://github.com/mcollina/autocannon</a> (By Matteo Collina)</li><li>0x — <a href="https://github.com/davidmarkclements/0x">https://github.com/davidmarkclements/0x</a> (By David Mark Clements)</li><li>Clinic — <a href="https://clinicjs.org/doctor/">https://clinicjs.org/doctor/</a> (From Nearform)</li></ol><h4><strong>Additional Reading</strong></h4><p>Some helpful articles and videos on node performance</p><ol><li>Keeping Node.js Fast: Tools, Techniques, And Tips For Making High-Performance Node.js Servers — <a href="https://www.smashingmagazine.com/2018/06/nodejs-tools-techniques-performance-servers/">https://www.smashingmagazine.com/2018/06/nodejs-tools-techniques-performance-servers/</a></li><li>Take Your HTTP Server to Ludicrous Speed [I] — <a href="https://www.youtube.com/watch?v=gltzZjKYK1I">https://www.youtube.com/watch?v=gltzZjKYK1I</a></li></ol><p>Title image GSLV-F08 liftoff © <a href="https://www.isro.gov.in/">https://www.isro.gov.in/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc9f2673455e" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/understanding-nodejs-performance-dc9f2673455e">Understanding Node.js Performance</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Write Your Own Flow Engine.]]></title>
            <link>https://medium.com/swlh/write-your-own-flow-engine-f7cda72074f3?source=rss-f86d8caa0c3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7cda72074f3</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[engine-flow]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[fbp]]></category>
            <dc:creator><![CDATA[Hari Narasimhan]]></dc:creator>
            <pubDate>Sat, 06 Feb 2021 11:26:31 GMT</pubDate>
            <atom:updated>2022-10-28T06:13:10.408Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Flow Engine" src="https://cdn-images-1.medium.com/max/871/1*L4A2ij38lcT1e7t5UFf6Jg.png" /></figure><p>Anyone who has written software platforms would appreciate the need for configurable business logic. The most common business logic is a series of operations. For example, the order processing business logic checks the stock at hand before placing an order. Reorder is initiated based on the stock threshold. Hold your thoughts on these keywords ‘business logic’, ‘before’, and, ‘after’ we will revisit them soon.</p><p>Flow-based programming is a very natural means of expressing business logic flow. We can imagine flows like a network of interconnected nodes. Each node performs a well-defined task and passes on the context to the next node until completion.</p><p>Flow engines play a significant role in the new development paradigms. The no-code/low-code platforms are gaining prominence. Flow engines help code complex business flows with WYSIWYG tools.</p><p>Alright, let us try and build a flow engine. Here are a few terms that we will use to define our flow engine</p><p>Flow: A graph data structure containing a set of nodes and connections between them (edge). In Graph terminology, we call them Directed Acyclic Graphs (DAG)</p><p>Runtime: The engine&#39;s core executes the flow nodes and transitions to the next node on completion. The run time passes the context and the message to all nodes.</p><p>Task: A task definition provides specific functionality. Task receives the context and message from the runtime, performs its work, and passes the control back to the runtime.</p><p>Here is a JSON snippet that defines a flow</p><pre><br>nodes: [<br> {<br> id: ‘first’,<br> name: ‘firstNode’,<br> type: ‘readApi’,<br> props: { url: ‘<a href="https://randomuser.me/api&#39;">https://randomuser.me/api’</a> }<br> },<br> {<br> id: ‘second’,<br> name: ‘secondNode’,<br> type: ‘readAsync’,<br> props: {}<br> },<br> {<br> id: ‘third’,<br> name: ‘thirdNode’,<br> type: ‘read’,<br> props: { url: ‘<a href="https://randomuser.me/api/&#39;">https://randomuser.me/api/’</a> }<br> },<br> {<br> id: ‘fourth’,<br> name: ‘fourthNode’,<br> type: ‘read’,<br> props: {}<br> }<br> ],<br> connections: [<br> { source: ‘first’, target: ‘second’ },<br> { source: ‘second’, target: ‘third’ },<br> { source: ‘second’, target: ‘fourth’ }<br> ]<br> }</pre><p>Each node has a type, which defines its behavior. We configure the node behavior via props (properties)</p><p>We will implement the flow engine in NodeJS and leverage the event-driven architecture and promises. From here on, some understanding of JavaScript and NodeJS will be helpful.</p><p><strong>Flow</strong></p><pre>class Flow {<br> constructor (flow) {<br> this._flow = flow<br> }<br> get flow () {<br>   return this._flow || {}<br> }</pre><pre> get nodes () {<br>   return this._flow.nodes || []<br> }</pre><pre> get connections () {<br>   return this._flow.connections || [] <br> }</pre><pre> getNode (id) {<br>   return this.nodes.find((n) =&gt; n.id === id)<br> }</pre><pre> getInboundConnections (nodeId) {<br>   return this.connections.filter(© =&gt; c.target === nodeId).map(n =&gt; n.source)<br> }</pre><pre> getOutboundConnections (nodeId) {<br>   return this.connections.filter(© =&gt; c.source === nodeId).map(n =&gt; n.target)<br> }</pre><pre> get startNode () {<br>   // Find a node with no inbound connections<br>   const starts = this.nodes.filter((n) =&gt; {<br>   const inbound = this.getInboundConnections(n.id)<br>   return inbound.length === 0<br>   })<br>   <br>  if (starts.length &gt; 1) {<br>     throw new Error(‘FlowEngine does not support multiple start nodes’)<br>   }</pre><pre>  return starts[0] || null<br> }<br> <br> get endNode() {<br>   const nodesCount = this.nodes.length<br>   if (nodesCount === 0) {<br>     return null<br>   }<br>   return this.nodes[nodesCount — 1]<br> }<br>}</pre><pre>module.exports = Flow</pre><p>This class abstracts the flow data structure and provides methods to <br>1) Fetch outbound connections<br>2) Fetch inbound connections<br>3) Fetch the start node<br>4) Fetch the end node<br>5) Fetch a node by its id</p><p><strong>Runtime</strong></p><pre>const EventEmitter = require(‘events’)<br>const Flow = require(‘./flow’)</pre><pre>const STATUS = {<br> RUNNING: ‘RUNNING’,<br> COMPLETED: ‘COMPLETED’,<br> ERROR: ‘ERROR’<br>}</pre><pre>class Runtime extends EventEmitter {<br> constructor ({flow, context, tasks} = {}) {<br> super()<br> this._flow = new Flow(flow)<br> this._context = context<br> this._tasks = tasks<br> this._isRunning = false<br> this._started = false<br> this._completed = false<br> this._state = {}<br> }</pre><pre>get context () {<br> return this._context<br> }</pre><pre>set context (context) {<br> this._context = context<br> }</pre><pre>get flow () {<br> return this._flow<br> }</pre><pre>get state () {<br> return this._state<br> }<br> <br> get tasks () {<br> return this._tasks<br> }</pre><pre>get startNode () {<br> return this.flow.startNode<br> }</pre><pre>get isRunning () {<br> return this._isRunning<br> }</pre><pre>set isRunning (isRunning) {<br> this._isRunning = isRunning<br> }</pre><pre>allNodesTraversed () {<br> const completed = Object.keys(this.state).filter((s) =&gt; this.state[s].status === STATUS.COMPLETED)<br> return completed.length === this.flow.nodes.length<br> }</pre><pre>start () {<br> this.runNode({node: this.startNode})<br> this.isRunning = true<br> this.emit(‘start’, {node: this.startNode})<br> }</pre><pre>async runNode ({node, prevNode, message = {}} = {}) {<br> let canRun = false<br> if (prevNode) {<br> const inboundConnections = this.flow.getInboundConnections(node.id)<br> const allCompleted = inboundConnections.filter(© =&gt; this.state[c].status === STATUS.COMPLETED)<br> if (inboundConnections.length === allCompleted.length) {<br> canRun = true<br> }<br> } else {<br> canRun = true<br> }</pre><pre>if (canRun) {<br> this.state[node.id] = { status: STATUS.RUNNING }<br> const task = this.tasks.get(node.type)<br> try {<br> const result = await task.run({node, context: this.context, message})<br> this.completeNode({ node, message: result })<br> } catch (error) {<br> this.emit(‘error’, { error })<br> throw error<br> }<br> }<br> }</pre><pre>completeNode({node, message}) {<br> this.state[node.id].status = STATUS.COMPLETED<br> <br> const outboundConnections = this.flow.getOutboundConnections(node.id)<br> <br> if (this.allNodesTraversed()) {<br> this.isRunning = false<br> this.emit(‘end’, { message })<br> return<br> }<br> <br> // We have not reached the end, let us continue<br> outboundConnections.map((outNode) =&gt; this.runNode({<br> node: this.flow.getNode(outNode),<br> prevNode: node,<br> message<br> }))<br> }<br>}</pre><pre>module.exports = Runtime</pre><p>Runtime is the heart and soul of the flow engine. It takes a flow, a context, and task definitions as input and returns a flow engine instance. The runtime extends NodeJS events to make the flow engine work asynchronously. The tasks implement the node behavior. The good thing about this pattern is that we can create any node behavior and inject it into the flow. It is fully extensible and allows us to create custom behaviors.</p><p><strong>Conventions for a task node</strong></p><p>For all of this to work, we need to follow some conventions. Importantly we need a standard way to pass information between the nodes. The nodes should also return the result of their execution consistently. The tasks receive three parameters.</p><ul><li>node — To pass configurations as properties (props)<br>context — Provides the execution context, such as access to some external libraries.</li><li>message — message passed from the previous node. For a start node, the message may be empty.</li><li>The tasks expose a method called run. The runtime uses the run method to execute the task.</li></ul><p><strong>Try it out<br></strong>Let us take it to the test. We will implement two nodes.</p><figure><img alt="An example flow" src="https://cdn-images-1.medium.com/max/871/1*UBfZsyQC6-hSa5XG57NqcA.png" /></figure><p><strong>Fetch User<br></strong>The first node will fetch a user (from random user API) and pass on the first name, last name, and title to the next node.</p><pre>const Task = require(‘../../index’).Task<br>const axios = require(‘axios’)</pre><pre>class FetchUser extends Task {<br> async run ({node, context, message} = {}) {<br> const url = node.props.url<br> const result = await axios.get(url)<br> return result.data.results[0].name<br> }<br>}</pre><pre>module.exports = FetchUser</pre><p>Capitalize Name<br>The node capitalizes the first name and last name it receives</p><pre>const Task = require(‘../../index’).Task</pre><pre>class CapitalizeUser extends Task {<br> async run ({node, context, message} = {}) {<br> return {title: message.title, first: message.first.toUpperCase(), last: message.last.toUpperCase()}<br> }<br>}</pre><pre>module.exports = CapitalizeUser</pre><p>And a simple flow definition in JavaScript.</p><pre>{<br> nodes: [{<br>   id: ‘first’,<br>   name: ‘fetch a user’,<br>   type: ‘fetchUser’,<br>   props: { url: ‘<a href="https://randomuser.me/api&#39;">https://randomuser.me/api&#39;</a> }<br> },{<br>   id: ‘second’,<br>   name: ‘Capitalize user names’,<br>   type: ‘capitalizeUser’,<br>   props: {}<br> }],<br> connections: [<br>   { source: ‘first’, target: ‘second’ }<br> ]<br>}</pre><p>If we execute this flow, with the flow engine</p><pre>const context = {}</pre><pre>const flowEngine = new FlowEngine({<br> flow: complexFlow,<br> context,<br> tasks: { <br>    fetchUser: new FetchUser(), <br>    capitalizeUser: new CapitalizeUser() }<br>})</pre><pre>const runtime = flowEngine.run()</pre><pre>runtime.on(‘end’, (result) =&gt; {<br> console.log(JSON.stringify(result, undefined, 2))<br>})</pre><p>The result will be somewhat similar to the JSON data given below.</p><pre>{<br> “message”: {<br> “title”: “Mr”,<br> “first”: “PABLO”,<br> “last”: “RAMOS”<br> }<br>}</pre><p><strong>Conclusion</strong><br>Flow-based programming (FBP) is a powerful concept. In this era of no-code-based platforms, FBP and flow engines are beneficial tools for solving business problems. There are many open-source FBP engines available today (‘node-red, ‘no-flo’, etc.). The appreciation of these engines improves if we understand how they work. This article is a small step toward understanding the inner workings of a flow engine.</p><p>The code for this article is available here <a href="https://github.com/hari-narasimhan/flow-engine">https://github.com/hari-narasimhan/flow-engine</a>.</p><p>Please feel free to share and comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7cda72074f3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/write-your-own-flow-engine-f7cda72074f3">Write Your Own Flow Engine.</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[Nifty UI/UX Prototypes with Microsoft PowerPoint]]></title>
            <link>https://harin76.medium.com/nifty-ui-ux-prototypes-with-microsoft-powerpoint-7e0e41c2c2f?source=rss-f86d8caa0c3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e0e41c2c2f</guid>
            <category><![CDATA[powerpoint]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[prototyping]]></category>
            <category><![CDATA[ui]]></category>
            <dc:creator><![CDATA[Hari Narasimhan]]></dc:creator>
            <pubDate>Sat, 10 Jun 2017 09:57:28 GMT</pubDate>
            <atom:updated>2017-06-10T09:57:28.517Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Have some good ideas, and want to see how these ideas might work out? But do not want to go into a full fledged UI/UX design, what would you do?</blockquote><blockquote>We generally start with paper sketches, and move to a low fidelity design before embarking upon a grand UI/UX exercise. There are times when one may need something better than paper prototypes, to bring our the life in the prototype.</blockquote><blockquote>Microsoft PowerPoint is a wonderful tool for creating rapid UI/UX prototypes.</blockquote><h3>Setup</h3><p>First thing to do is to avoid the default transition in PowerPoint, i.e. slide transitions through arrow keys and clicks.</p><p>Go to <strong>Slide Show → Setup Slide Show</strong> and change the show type to <strong><em>Browsed at a Kiosk (full screen)</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*WKsJpN0pSQFFgDdnuT4ivA.png" /><figcaption>Set Show Type</figcaption></figure><p>For Screen Size, 16:9 ratios are generally good, it is the default in PowerPoint 2013 and 2016. You may want to check your screen size in the <strong>Design → Slide Size</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/159/1*sl87hudLh4a-ihSbCeaWLg.png" /><figcaption>Select 16:9 Ratio</figcaption></figure><h3>Screens (or Slides!) and navigation</h3><p>Set the layout of the slide to blank and build your screens using shapes, storyboards and clip arts.</p><p>To set up navigation add hyperlinks to any object on the screen by right clicking on the object and setting the links. I use a transparent blue coloured boxes to indicate hot spots and add hyperlinks to the boxes.</p><p>I generally do not use too much animation, I find them quite distracting.</p><h3>Tips for linking</h3><p>Since the slides are blank, when we try to link we see references to the slides as <em>Slide 1, Slide 2,</em> etc. For smaller projects this may be fine, but for larger projects proper slide names will be helpful.</p><p>To add names (title) to the slides, select outline view from view menu or you can toggle it in the bottom bar (View → Outline) . In the outline view click next to the slide and add a meaningful name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rSzyjXEjgnDeFKAqDjthyw.png" /><figcaption>Outline View — Click and add title</figcaption></figure><p>One immediate problem is that, the title is placed inside the slide and it obstructs the screen. Move the title to the top of the slide as shown in the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MiUAFtl6SkYRth3u2f_2kQ.png" /><figcaption>Move title to the top of the title, outside the view.</figcaption></figure><h3>Interaction</h3><p>Core of the interaction is done through hyperlinking. Add transparent coloured boxes on areas in the slide to indicate hot spots and add hyperlink to create a transition from one slide to another. Please note that these transparent boxes need not be added, I find them helpful since the boxes provide visual clue for hot spots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*GEXK-SodcdjiMAd2FXCFww.png" /><figcaption>Insert Hyperlink — Named Slides help identify the right slide for linking.</figcaption></figure><h3>Result</h3><p>Voila, a quick and clean way to create nifty low fidelity UI/UX prototypes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NGudfjxEHffAmRVK7qKQtg.gif" /><figcaption>The Result</figcaption></figure><h3>Conclusion</h3><p>The technique is not limited to Microsoft PowerPoint, it can be done on Keynote, Open office presentation or possibly even on Google presentation. I found PowerPoint most powerful and easy to use. Also PowerPoint 2016 has a great <em>Story boarding</em> feature allowing creation and sharing of visual components for prototypes, a very good feature to have indeed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e0e41c2c2f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My India, My Dream]]></title>
            <link>https://medium.com/series/my-india-my-dream-15acd6310ced?source=rss-f86d8caa0c3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/15acd6310ced</guid>
            <dc:creator><![CDATA[Hari Narasimhan]]></dc:creator>
            <pubDate>Mon, 05 Jun 2017 16:34:02 GMT</pubDate>
            <atom:updated>2017-06-05T17:41:54.990Z</atom:updated>
            <content:encoded><![CDATA[<h3>ISRO Launches GSLV MK-III</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1GlywnAhhc3byqmjK5LRHg.png" /><figcaption>Image Courtesy: <a href="http://www.isro.gov.in/">http://www.isro.gov.in/</a></figcaption></figure><p>It is a proud moment for every Indian, our ISRO has successfully launched the Geosynchronous Satellite Launch Vehicle (GSLV) Mark III on Monday 5th June 2017. The launch makes our dream of manned space missions a step closer to reality.</p><p>Nick named “fat boy”, GSLV MK-III can lift 4 tonne payload to a geosynchronous transfer orbit of 36,000 km or 10 tonne payload to a 600 km low earth orbit.</p><p>Sincere thanks to each and every member of ISRO team having made this happen.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15acd6310ced" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generate Vue.js components from a JSON / JavaScript DOM Structure]]></title>
            <link>https://harin76.medium.com/generate-vue-js-components-from-a-json-javascript-dom-structure-a76534478d15?source=rss-f86d8caa0c3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a76534478d15</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Hari Narasimhan]]></dc:creator>
            <pubDate>Sun, 04 Jun 2017 16:29:22 GMT</pubDate>
            <atom:updated>2017-06-13T07:57:45.991Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>At times we need the ability to store a document structure and re-create it. For instance when we create WYSIWYG designer or a rich text editor, we may have to store the document structure in server and re-create the same for editing.</blockquote><blockquote>Let us look into the <strong>render</strong> method of the Vue.js component and use the interface the render method exposes (createElement), to build components from JSON or JavaScript object.</blockquote><h3>The render function</h3><p>The Vue.js component provides a low level “render” property. The property is actually a function frequently referred to as createElement. The createElement function takes three arguments</p><ul><li>A tag name</li><li>Properties for the tag</li><li>Children — [VNodes] Array of children</li></ul><p>Let’s leverage render method and the createElement function to render a JSON / JavaScript DOM structure.</p><p>refer: <a href="https://vuejs.org/v2/guide/render-function.html#ad">https://vuejs.org/v2/guide/render-function.html#ad</a></p><h3>DOM Structure</h3><p>We need structure to recursively describe a document. The sketchy specification of the node of the document is given below. Each DOM node has following attributes</p><ul><li>tagName — contains the html tag to render</li><li>properties — contains the attributes and other properties related to the html tag</li><li>children — contains the array of DOM structure</li><li>textNode — contains the textual content of a html tag</li></ul><p>A node can contain either <em>array of other nodes</em> or a <em>text node</em></p><pre>{<br>  tagName: &#39;div&#39;,<br>  children: [<br>    {<br>      tagName: &#39;h1&#39;,<br>      textNode: &#39;Great News&#39;<br>    },<br>    {<br>      tagName: &#39;h3&#39;,<br>      textNode: &#39;YOU CAN CREATE VUE COMPONENTS OUT OF JSON&#39;<br>    },         <br>    {<br>      tagName: &#39;a&#39;,<br>      properties: {<br>        attrs: {href: &#39;#&#39;}<br>      },<br>      textNode: &#39;Vue.js&#39;<br>    }<br>  ]<br>};</pre><h3>Recursive function to create VNode</h3><p>The Vue.js component’s render method returns a VNode. We have to write a recursive function that takes the DOM structure and createElement function and recursively constructs the entire structure as a VNode representation.</p><p>Please note that we have renamed <strong>createElement </strong>function to a shorter name “<strong>h</strong>”, it is a common practice to do so, to avoid repeated typing of createElement in your code.</p><p>We will call our recursive function <strong>createComponent</strong></p><pre>/**<br>* Create component is a recursive function that takes a DOM structure<br>* and a rendering function (of vue.js) and returns a Vuejs component.<br>*/<br>const createComponent = (dNode, h) =&gt; {<br>  // Handle empty elements and return empty array in case the dNode passed in is empty<br>  if (_.isEmpty(dNode)) {<br>    return [];<br>  }</pre><pre>// if the el is array call createComponent for all nodes<br>  if (_.isArray(dNode)) {<br>    return dNode.map((child) =&gt; createComponent(child, h))<br>  }</pre><pre>let children = []; <br>  <br>  if (dNode.children &amp;&amp; dNode.children.length &gt; 0) {<br>    dNode.children.forEach((c) =&gt; {<br>      if (_.isString(c)) {<br>        children.push(c)<br>      } else {<br>        children.push(createComponent(c, h))<br>      }<br>    });<br>  }<br>  // Need to clone <br>  const properties = _.cloneDeep(dNode.properties)<br>  return h(dNode.tagName, properties, children.length &gt; 0? children : dNode.textNode)<br>}</pre><p>The createComponent checks for empty dNode and handles it appropriately. We check if dNode is an array and call createComponent on each element. If dNode has children, each child’s VNode representation is created through recursive call.</p><p>Care must be taken to clone the properties. The reason is that, the nodes can be set as a property on the component and they will have watchers attached to them. Vue.js will complain about duplicate watchers.</p><h3>The Component</h3><p>Now we will finish with a component that calls createComponent from its render method.</p><pre>/**<br>* A sample component uses the recursive createComponent to render a DOM / List of DOM nodes<br>*/<br>const MyComponent = Vue.component(&#39;my-component&#39;, {<br>  render: function (h) {<br>    return createComponent(this.nodes, h)<br>  },<br>  props: {<br>    nodes: {<br>      type: Object,<br>      required: true<br>    }<br>  }<br>});</pre><p>Here the MyComponent implements a render method, which uses the createComponent function to create VNodes and render them. The nodes themselves are passed in as property.</p><p>An example component that uses MyComponent shown below</p><pre>new Vue({<br>  el: &#39;#app&#39;,<br>  template: &#39;&lt;MyComponent :nodes=&quot;nodes&quot;/&gt;&#39;,<br>  components: { MyComponent },<br>  data: function(){<br>    return {<br>      nodes: {<br>        tagName: &#39;div&#39;,<br>        children: [<br>          {<br>            tagName: &#39;h1&#39;,<br>            textNode: &#39;Great News&#39;<br>          },<br>          {<br>            tagName: &#39;h3&#39;,<br>            textNode: &#39;YOU CAN CREATE VUE COMPONENTS OUT OF JSON&#39;<br>          },         <br>          {<br>            tagName: &#39;a&#39;,<br>            properties: {<br>              attrs: {href: &#39;#&#39;}<br>            },<br>            textNode: &#39;Vue.js&#39;<br>          }<br>        ]<br>      }<br>    }<br>  }<br>});</pre><h3>Result</h3><p>We have taken a plain JSON / JavaScript node structure and created a HTML document out of it. As mentioned earlier, this will be helpful if we have a serialized version of a document that we need to recreate.</p><p>Much more can be done such as attaching events to the created VNodes, styling them etc, I hope you can explore all these further.</p><p>The jsbin for the example component can be found at</p><p><a href="http://jsbin.com/teqoxi/edit">http://jsbin.com/teqoxi/edit</a></p><p>Thanks for reading along, if you find this useful please like and share. Happy coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a76534478d15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a grid component in Vue.js]]></title>
            <link>https://harin76.medium.com/building-a-grid-component-in-vue-js-e1548e5a0992?source=rss-f86d8caa0c3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1548e5a0992</guid>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[grid]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Hari Narasimhan]]></dc:creator>
            <pubDate>Sun, 21 May 2017 17:45:19 GMT</pubDate>
            <atom:updated>2017-05-21T17:45:19.595Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bdJAwpEQ2RTNEArKFh6CtA.png" /></figure><p>Grid components are notoriously complex to build. There are so many aspects and it takes forever to build a perfect one. Having said that, building a grid for your specific needs should not be that difficult.</p><p>In this article, we will explore how to build a grid component “Griddy” in Vue.js. The overall idea is to explore ways of building this component, so that people can look at their specific use cases and extent it.</p><h4>Warning</h4><p>The component is by no means <strong><em>production ready, </em></strong>this is strictly for educational purpose only.</p><h3>Concepts we will explore.</h3><p>We will explore the following concepts, they are just a minimum set and we will be just scratching the surface.</p><ul><li>Fixed Header</li><li>Resize columns</li><li>Fetching data</li><li>Navigation</li></ul><h3>Why Vue.js?</h3><p>I simply love it, it is fun to code in Vue.js, it extends itself very well for developing UI components.</p><p>We will use the .vue file for defining components. The .vue file will be split into template, script and style sections.</p><h3>The Markup</h3><pre>&lt;template&gt;<br>  &lt;div class=&quot;wrapper&quot; :style=&quot;{width: width, height: height + &#39;px&#39;}&quot;&gt;<br>    &lt;div class=&quot;grid-header&quot;&gt;<br>      &lt;span class=&quot;title&quot;&gt;{{title}}&lt;/span&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;grid-body&quot; :style=&quot;{height: tableBodyHeight + &#39;px&#39;}&quot;&gt;<br>      &lt;div class=&quot;table-header-wrapper&quot;&gt;<br>        &lt;table class=&quot;table-header&quot;&gt;<br>          &lt;tr&gt;<br>            &lt;th v-for=&quot;column in columns&quot; :data-column-name= &quot;column.name&quot; :width=&quot;column.width ? column.width : &#39;100&#39;&quot;&gt; {{column.label}}&lt;/th&gt;<br>          &lt;/tr&gt;<br>        &lt;/table&gt;<br>      &lt;/div&gt;<br>      &lt;div class=&quot;table-body-wrapper&quot;&gt;<br>        &lt;table class=&quot;table-body&quot;&gt;<br>          &lt;tr v-for=&quot;row in rows&quot;&gt;<br>            &lt;td v-for=&quot;column in columns&quot; :width=&quot;column.width ? column.width : &#39;100&#39;&quot;&gt; {{val(row, column.field)}}&lt;/td&gt;<br>          &lt;/tr&gt;<br>        &lt;/table&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;grid-footer&quot;&gt;<br>      &lt;div v-if=&quot;!error&quot;&gt;<br>        &lt;span&gt;&lt;a <a href="http://twitter.com/click">@click</a>=&quot;handlePrevious&quot;&gt;Previous&lt;/a&gt;&lt;/span&gt;<br>        &lt;span&gt;{{page}}&lt;/span&gt;<br>        &lt;span&gt;&lt;a <a href="http://twitter.com/click">@click</a>=&quot;handleNext&quot;&gt;Next&lt;/a&gt;&lt;/span&gt;<br>      &lt;/div&gt;<br>      &lt;span v-else&gt;{{error}}&lt;/span&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;</pre><p>The template has a wrapper to hold the grid component. The wrapper has a its overflow-y set to scroll. The wrapper contains grid-header, grid-body and grid-footer.</p><p>The grid-header can be used for displaying title, holding buttons etc, our example just has the title. The footer can be utilised for pagination controls. In our example the footer has a previous and next link and displays current page number in the centre.</p><p>The grid body, contains two tables. The two tables are required to create a fixed header effect. The technique for this has been adapted from the article <a href="https://joshondesign.com/2015/05/23/csstable">“The Holy Grail: Pure CSS Scrolling Tables With Fixed Header”</a> by Josh Marinacci. I am not going to explain the CSS in detail, I request the reader to wade through the code and Josh’s article.</p><h3>The code</h3><p>The Vue.js component takes up the following properies</p><ul><li>title — Title for the grid</li><li>columns — Metadata for the columns containing name, field to pluck from response and column width</li><li>width — Width of the grid</li><li>height — Height of the grid</li><li>resourceURL — API endpoint to fetch the data</li></ul><p>When the component is mounted, we initialise the component</p><pre>mounted () {<br>    const vm = this<br>    vm.header = vm.$el.getElementsByClassName(&#39;table-header&#39;)[0]<br>    vm.body = vm.$el.getElementsByClassName(&#39;table-body&#39;)[0]<br>    vm.setResizeGrips()<br>    vm.syncColumnWidths()<br>  },</pre><p>The reference to table-header and table-footer are stored in the component. The setResizeGrips method as its name suggests adds the resize grips to the header table. The syncColumnWidths method synchronises the column widths between the header table and body table. As you will see, syncColumnWidths will be called each time the header column is resized.</p><pre>setResizeGrips () {<br>      const vm = this<br>      const headerCols =   Array.from(vm.header.getElementsByTagName(&#39;th&#39;))<br>      headerCols.forEach((th) =&gt; {<br>        th.style.position = &#39;relative&#39;</pre><pre>const grip = document.createElement(&#39;div&#39;)<br>        grip.className = &#39;grip&#39;<br>        grip.innerHTML = &#39;&amp;nbsp&#39;<br>        grip.style.top = 0<br>        grip.style.right = 0<br>        grip.style.bottom = 0<br>        grip.style.width = &#39;5px&#39;<br>        grip.style.position = &#39;absolute&#39;<br>        grip.style.cursor = &#39;col-resize&#39;<br>        grip.addEventListener(&#39;mousedown&#39;, this.onMouseDown)<br>        th.appendChild(grip)<br>        vm.grips.push(grip)<br>      })</pre><pre>      document.addEventListener(&#39;mousemove&#39;, this.onMouseMove)<br>      document.addEventListener(&#39;mouseup&#39;, this.onMouseUp)<br>    }</pre><p>The mouse events are attached to each grip and the document.</p><pre>syncColumnWidths () {<br>      const vm = this<br>      const headerCols = Array.from(vm.header.getElementsByTagName(&#39;th&#39;))<br>      const widths = headerCols.map((h) =&gt; h.width ? h.width : h.clientWidth)<br>      const bodyCols = Array.from(vm.body.querySelectorAll(&#39;tr:first-child&gt;td&#39;))<br>      bodyCols.forEach((c, i) =&gt; {<br>        c.width = widths[i] + &#39;px&#39;<br>      })<br>    }</pre><p>Mouse events</p><pre>onMouseDown (e) {<br>      const vm = this<br>      vm.thElm = e.target.parentNode<br>      vm.startOffset = vm.thElm.offsetWidth - e.pageX<br>    },<br>    onMouseMove (e) {<br>      const vm = this<br>      if (vm.thElm) {<br>        const colName = vm.thElm.getAttribute(&#39;data-column-name&#39;)<br>        const width = vm.startOffset + e.pageX</pre><pre>if (vm.greaterThenMinWidth(colName, width)) {<br>          vm.thElm.width = width + &#39;px&#39;<br>          vm.syncColumnWidths()<br>        }<br>      }<br>    },<br>    onMouseUp (e) {<br>      const vm = this<br>      vm.thElm = undefined<br>      vm.syncColumnWidths()<br>    }</pre><p>The code for syncing the header table and body table was inspired from jQuery <a href="http://www.bacubacu.com/colresizable/">colResizable</a> plugin.</p><p>Since we have added event listeners to DOM elements, we have to be responsible enough to unregister them when the component is destroyed. We add the code in beforeDestroy hook. We had cached the grips earlier, we will use the same to remove event listeners.</p><pre>beforeDestroy () {<br>    const vm = this<br>    vm.grips.forEach((grip) =&gt; grip.removeEventListener(&#39;mousedown&#39;, vm.onMouseDown))<br>    document.removeEventListener(&#39;mousemove&#39;, vm.onMouseMove)<br>    document.removeEventListener(&#39;mouseup&#39;, vm.onMouseUp)<br>  }</pre><p>The data fetching us done using the vue-resource plugin and the resourceURL property. This is very rudimentary, for a robust implementation one must implement the concept of a store to abstract the data fetches.</p><p>Our data fetching is simple</p><pre>fetchData () {<br>      this.resource.get({results: this.records, page: this.page}).then((response) =&gt; {<br>        this.rows = response.body.results<br>      }).catch(() =&gt; {<br>        this.error = &#39;Error occured while trying to fetch data&#39;<br>      })<br>    }</pre><p>I am not going to explain the helper methods, like handlePrevious click etc they are very simple, kindly follow the code.</p><p>Though I have not explicitly shown how the component can be used by the consumer, it is very easy and straightforward.</p><pre>&lt;griddy :columns=&quot;columns&quot;<br>            :resourceURL = &quot;resourceURL&quot;<br>            width=&quot;200&quot;<br>            height=&quot;500&quot;&gt;<br>&lt;/griddy&gt;</pre><p>Where columns contains the column meta data and resource url contains API end point to query</p><pre>resourceURL: &#39;<a href="https://randomuser.me/api&#39;">https://randomuser.me/api&#39;</a>,<br>      columns: [<br>        {name: &#39;title&#39;, label: &#39;Title&#39;, field: &#39;name.title&#39;, width: &#39;100&#39;, type: &#39;text&#39;, isMandatory: true},<br>        {name: &#39;firstName&#39;, label: &#39;First Name&#39;, field: &#39;name.first&#39;, width: &#39;200&#39;, type: &#39;text&#39;, isMandatory: true},<br>        {name: &#39;lastName&#39;, label: &#39;Last Name&#39;, field: &#39;name.last&#39;, width: &#39;200&#39;, type: &#39;text&#39;, isMandatory: true},<br>        {name: &#39;dataOfBirth&#39;, label: &#39;Date of Birth&#39;, field: &#39;dob&#39;, type: &#39;date&#39;, width: &#39;200&#39;, format: &#39;yyyy-MM-dd&#39;}<br>      ]</pre><h3>Result</h3><p>Something pretty neat for 200+ lines of HTML, JS and CSS, there is a huge scope for improvement. I recently read a data grid design article by Andrew Coyle titled “ <a href="https://uxdesign.cc/design-better-data-tables-4ecc99d23356">Design Better Data Tables</a>”, it was a comprehensive set of design patterns for data tables. I wish someday that our humble grid control implements all those patterns.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FJlgwSGxrExA%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DJlgwSGxrExA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FJlgwSGxrExA%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/059bde5579e3bd470e45f6786b4a27bc/href">https://medium.com/media/059bde5579e3bd470e45f6786b4a27bc/href</a></iframe><p>I hope this gave you an insight into how a grid component can be constructed. Please feel free to drop in some comments for suggestions, improvements etc.</p><p>The code for the grid component is available at <a href="https://github.com/harin76/griddy">https://github.com/harin76/griddy</a></p><h3>Acknowledgements &amp; Credits</h3><ol><li>Josh Marinacci — For <a href="https://joshondesign.com/2015/05/23/csstable">The Holy Grail: Pure CSS Scrolling Tables With Fixed Header</a></li><li>Alvaro Prieto Lauroba — <a href="http://www.bacubacu.com/colresizable/">colResizable</a> jQuery Plugin</li><li>VanillaJS — DOM manipulations</li><li>Andrew Coyle — <a href="https://uxdesign.cc/design-better-data-tables-4ecc99d23356">Design Better Data Tables</a></li><li>randomuser.me — REST API for testing.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1548e5a0992" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Embrace Automation]]></title>
            <link>https://harin76.medium.com/embrace-automation-7fbbed7deda9?source=rss-f86d8caa0c3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fbbed7deda9</guid>
            <category><![CDATA[it-industry]]></category>
            <category><![CDATA[career-development]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Hari Narasimhan]]></dc:creator>
            <pubDate>Sat, 20 May 2017 12:10:57 GMT</pubDate>
            <atom:updated>2017-05-23T01:47:55.688Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XcmcyS9t7b-1_SaZ8JnC_g.jpeg" /><figcaption>Embrace Automation</figcaption></figure><blockquote><em>Why program by hand in five days what you can spend five years of your life automating? — Dr Terence Parr</em></blockquote><p>There is a huge sense of anxiety amongst people from IT industry these days. Everyday we hear news of people made redundant, potential job cuts and intelligent machines taking over jobs. While I am not sure how many have lost their jobs, or will in the near future. I am certain that it will happen and we have to be prepared.</p><p>What’s happening around us is nothing new, it is just the proof that humanity is evolving continuously. Just as our ancestors made fire, invented wheel, transitioned from horses to steam engines and cars. Evolutions eradicates existing jobs and creates new ones. Survival of the fittest applies to all of us, no one is an exception.</p><p>Let is step into our own industry. The growth, especially in the last decade and a half has been humongous. As the industry grew, tools and infrastructure have matured. Our insatiable appetite for delivering better products faster and faster has resulted in need to automate even more. Over last 5–6 years, automation in UI coding, service delivery, integration and maturity of dev-ops practices have improved delivery pace exponentially.</p><p>Sadly, this has resulted in some of the traditional skills to be not required. What was done with 15–20 people team 15 years ago is easily accomplished by 5–6 member teams now, thanks to better tools and automation. As lots of things can be done in shorter time, multiple roles have merged into one, for instance we have a full-stack developers instead of front-end and back-end developers.</p><p>So what does this all mean? well, in short to stay ahead of the curve we need to embrace automation and start wearing multiple hats. As a person embracing automation you immediately improve your value, by bringing in the capability to reduce delivery time and improve quality. It is also fun as the opening quote from Dr Terence Parr states it generates a lot of value.</p><p>What does this mean for various team members?</p><p>For technical team members, i.e developers / senior developers always find ways to automate anything you do, don’t hand code CRUD classes, generate them from specs. Use appropriate automation tools or even better write them to perform your work. Pick up some good books like <a href="https://www.manning.com/books/code-generation-in-action"><strong><em>Code Generation In Action By Jack Herrington</em></strong></a><strong><em> or </em></strong>explore how tools such as <a href="http://yeoman.io/"><strong><em>yeoman</em></strong></a> work.</p><p>For Managers and Senior Executives, use automation to plan, execute and control tasks. Encourage your team to embrace automation, work with them to identify repeatable tasks and help automating them. Consistently challenge yourself and your team to reduce the time taken to deliver.</p><p>What are the benefits? personally, I feel that embracing automation allows you to think in a more abstract sense. It helps you deliver a better quality product. It makes you special, wanted and relevant at all times. It is also extremely fun to automate and experience the result of the automation.</p><h3>Moral</h3><p>Automation is real, it will continue to exist as long as humanity exists. Adapt, learn to automate and stay on top of the pyramid. Remember, only the fittest survive. You can always choose to be the person who creates the automation which threatens to take your job away.</p><p><em>Photo Courtesy : www.pixabay.com</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fbbed7deda9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Tenancy with KoaJS and Mongo]]></title>
            <link>https://harin76.medium.com/multi-tenancy-with-koajs-and-mongo-4b09df372128?source=rss-f86d8caa0c3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b09df372128</guid>
            <category><![CDATA[multitenancy]]></category>
            <category><![CDATA[koajs]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Hari Narasimhan]]></dc:creator>
            <pubDate>Mon, 01 May 2017 14:50:48 GMT</pubDate>
            <atom:updated>2017-05-01T15:12:50.875Z</atom:updated>
            <content:encoded><![CDATA[<p>Multi-tenancy is all about supporting multiple tenants or customers for a single application. The core concept is that we attach a context to an in-coming request, which helps in identifying the tenant and respond accordingly.<br><br>There are three patterns for multi-tenancy, which are based on how infrastructure such as application servers and database servers and other components are shared. The three patterns are<br><br>1) Nothing Shared<br>2) Partially Shared<br>3) Everything shared<br><br>In the nothing shared model, each tenant have their own application server and database server. It is not the most efficient model since application server and database servers have an instance each per tenant. Maintenance of such a system with large tenant base would be very cumbersome. Mostly such systems are commissioned due to customer requests to have a completely isolated application for security reasons.<br><br>In partially shared model, the application server or the database server may have one instance per customer. Most of the times it would be the database server. The idea is to provide isolation at the data layer and leverage sharing of application servers.<br><br>In everything shared model, the application server and database servers are shared. The tenant identification is done through a tenant key in the database. <br><br>Well that is a small peek in to the theory, now let us build a partially shared multi-tenant application using koajs and mongodb, we will develop a set of restful service that uses subdomain to identify a tenant. Each tenant will have their own mongo database, and we will route to appropriate database based on subdomain from the incoming request.</p><p>Prerequisites: nodejs 7.8.0, npm 4.2.0 and mongodb native driver. Also we will be developing using koa 2.0 style with async and await.<br><br>I am assuming that mongodb 3.x is already installed or you can get hold of a hosted mongodb instance. <br><br>Setup the project<br>Create a directory and cd into it</p><pre>mkdir multi-tenant-example<br>cd multi-tenant-example</pre><p>Initialise project and install required npm modules</p><pre>npm init - y<br># The above command should create a basic package.json<br># let us now install required node modules<br>npm i -S koa koa-router@next koa-mount koa-body@2</pre><p>After installation check the dependencies section your package.json, it must look something like this</p><pre>&quot;dependencies&quot;: {<br>    &quot;koa&quot;: &quot;2.2.0&quot;,<br>    &quot;koa-body&quot;: &quot;2.0.0&quot;,<br>    &quot;koa-mount&quot;: &quot;3.0.0&quot;,<br>    &quot;koa-router&quot;: &quot;7.1.1&quot;<br>  }</pre><p>Now let us create the basic structure of the application</p><pre># create these files and add<br>touch index.js config.global.js config.development.js config.production.js config.test.js</pre><p><strong>Lets add configurations</strong></p><p>config/index.js</p><pre>&#39;use strict&#39;<br>const env = process.env.NODE_ENV || &#39;development&#39;<br>module.exports = require(&#39;./config.&#39; + env)</pre><p>config/config.global.js</p><pre>&#39;use strict&#39;<br>// Put some global (default) configurations here<br>const config = { app: {}, mongo: {} }<br>config.env = &#39;development&#39;<br>config.app.port = process.env.port || 3000<br>config.mongo.host = &#39;localhost&#39;<br>config.mongo.dbName = &#39;myApp&#39;<br>module.exports = config</pre><p>config/config.development.js</p><pre>&#39;use strict&#39;<br><br>const config = require(&#39;./config.global&#39;)<br><br>config.env = &#39;development&#39;<br>config.mongo.dbName = config.mongo.dbName + &#39;_dev&#39;<br><br>module.exports = config</pre><p>config/config.production.js</p><pre>&#39;use strict&#39;<br><br>let config = require(&#39;./config.global&#39;)<br><br>config.env = &#39;production&#39;<br>config.mongo.dbName = config.mongo.dbName + &#39;_prod&#39;<br><br>module.exports = config</pre><p>config/config.test.js</p><pre>&#39;use strict&#39;<br><br>let config = require(&#39;./config.global&#39;)<br><br>config.env = &#39;test&#39;<br>config.mongo.dbName = config.mongo.dbName + &#39;_test&#39;<br><br>module.exports = config</pre><p>With application config done, let us create the main application. Add the following set of code within app.js</p><p>/app.js</p><pre>&#39;use strict&#39;<br>const Koa = require(&#39;koa&#39;)<br>const mount = require(&#39;koa-mount&#39;)<br>const config = require(&#39;./config&#39;)<br><br>// Create the main application<br>const app = new Koa()<br><br>// Create a koa application for v1 services<br>const v1 = new Koa()<br>v1.use(require(&#39;./services&#39;).v1)<br><br>// mount the v1 app as a middleware in the<br>// main app<br>app.use(mount(&#39;/api/v1&#39;, v1))<br>module.exports = app</pre><p>Now let us create a task service, follow on</p><pre># cd into services directory<br>touch index.js<br><br># make a v1 directory &amp; cd into it<br>mkdir v1<br>cd v1<br><br>touch index.js tasks.js</pre><p>services/v1/tasks.js</p><pre>&#39;use strict&#39;<br>const koaBody = require(&#39;koa-body&#39;)()<br><br>const create = async function (ctx, next) {<br>  ctx.body = &#39;CREATE::TASK TBD&#39;<br>  return next()<br>}<br><br>const find = async function (ctx, next) {<br>  ctx.body = &#39;LIST::TASKS TBD&#39;<br>  return next()<br>}<br><br>exports.register = (router) =&gt; {<br>  // POST api/v1/tasks<br>  router.post(&#39;/tasks&#39;, koaBody, create)<br><br>  // GET api/v1/tasks<br>  router.get(&#39;/tasks&#39;, find)<br>}</pre><p>We have written two routes, one to create a task and another to list tasks, let is keep it minimal for now.</p><p>Add the code given below to services/v1/index.js</p><pre>&#39;use strict&#39;<br><br>const Router = require(&#39;koa-router&#39;)<br>const router = new Router()<br><br>require(&#39;./tasks&#39;).register(router)<br><br>module.exports = router.middleware()</pre><p>Finish up services by adding the following code into services/index.js</p><pre>&#39;use strict&#39;<br><br>exports.v1 = require(&#39;./v1&#39;)</pre><p>Let us add code to server.js to start the application</p><pre>&#39;use strict&#39;<br><br>const config = require(&#39;./config&#39;)<br>const app = require(&#39;./app&#39;)<br><br>app.listen(config.app.port, function () {<br>  console.log(&#39;services started at &#39; + config.app.port)<br>})</pre><p>Let is take what we have built so far for a spin</p><pre># type<br>node server.js</pre><p>Using postman, curl or any other tool check the endpoints</p><pre>curl http://localhost:3000/api/v1/tasks<br>curl -X POST http://localhost:3000/api/v1/tasks<br><br>should return<br><br>LIST::TASKS TBD<br><br>and<br><br>CREATE::TASK TBD<br><br>respectively</pre><p>Let us turn the focus to database, we will create a connection manager to handle connection pooling and a data access layer for models to query the database.</p><p>db/connectionMgr.js</p><pre>&#39;use strict&#39;<br>const _ = require(&#39;lodash&#39;)<br>const MongoDB = require(&#39;mongodb&#39;)<br>const MongoClient = MongoDB.MongoClient<br>const genericPool = require(&#39;generic-pool&#39;)<br><br>let pool<br><br>const defaultOptions = {<br>  host: &#39;localhost&#39;,<br>  port: 27017,<br>  db: &#39;test&#39;,<br>  max: 100,<br>  min: 1<br>}<br><br>exports.init = (options) =&gt; {<br>  options = _.assign({}, defaultOptions, options)<br>  let mongoUrl = options.uri || options.url<br><br>  if (!mongoUrl) {<br>    if (options.user &amp;&amp; options.pass) {<br>      mongoUrl = `mongodb://${options.user}:${options.pass}@{options.host}:${options.port}/${options.db}`<br>    } else {<br>      mongoUrl = `mongodb://${options.host}:${options.port}/${options.db}`<br>    }<br>  }<br>  pool = genericPool.createPool({<br>    create: () =&gt; MongoClient.connect(mongoUrl, {<br>      poolSize: 1,<br>      native_parser: true<br>    }),<br>    destroy: (client) =&gt; client.close()<br>  }, options)<br>}<br><br>exports.acquire = () =&gt; pool.acquire()<br>exports.release = (conn) =&gt; pool.release(conn)</pre><p>The connectionMgr uses generic-pool, so install it</p><p>With connection manager added, let us now add code for database access. This is where it becomes interesting. We will add a insert and find method, pay attention to the first two parameters of the data access methods the tenant and the collection.</p><p>The tenant parameter identifies the tenant specific database and the collection refers to the model’s collection.</p><p>db/index.js</p><pre>&#39;use strict&#39;<br>const ObjectID = require(&#39;mongodb&#39;).ObjectID<br>const to = require(&#39;await-to-js&#39;).default<br>const ConnectionMgr = require(&#39;./connectionMgr&#39;)<br><br>exports.find = (tenant, coll, query, page, limit) =&gt; {<br>  return new Promise(async (resolve, reject) =&gt; {<br>    // Acquire a connection<br>    const conn = ConnectionMgr.acquire()<br><br>    // When the connection is available, use it<br>    conn.then(async (mongo) =&gt; {<br>      limit = limit || 10<br>      page = page || 1<br>      query = query || {}<br>      const skip = page &gt; 0 ? ((page - 1) * limit) : 0<br>      try {<br>        const collection = mongo.db(tenant).collection(coll)<br>        const [error, result] = await to(collection.find(query)<br>                                .sort({_id: -1})<br>                                .skip(skip)<br>                                .limit(limit)<br>                                .toArray())<br>        if (error) {<br>          return reject(error)<br>        } else {<br>          return resolve({<br>            cursor: {<br>              currentPage: page,<br>              perPage: limit<br>            },<br>            data: result<br>          })<br>        }<br>      } catch (error) {<br>        reject(error)<br>      } finally {<br>        // Release the connection after  us<br>        ConnectionMgr.release(mongo)<br>      }<br>    })<br>  })<br>}<br><br>exports.insert = (tenant, coll, payload) =&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>    // Acquire a connection<br>    const conn = ConnectionMgr.acquire()<br>    conn.then(async (mongo) =&gt; {<br>      try {<br>        console.log(tenant, coll)<br>        const collection = mongo.db(tenant).collection(coll)<br>        const [error, result] = await to(collection.insert(payload))<br><br>        if (error) {<br>          return reject(error)<br>        } else {<br>          return resolve(result)<br>        }<br>      } catch (error) {<br>        console.log(error)<br>        reject(error)<br>      } finally {<br>        ConnectionMgr.release(mongo)<br>      }<br>    })<br>  })<br>}</pre><p>Let us add the model, here model is a very loose definition we are basically going to write static accessor methods.</p><p>models/task.js</p><pre>&#39;use strict&#39;<br>const to = require(&#39;await-to-js&#39;).default<br>const DB = require(&#39;../db&#39;)<br><br>const COLLECTION = &#39;tasks&#39;<br><br>class Task {<br>  static create (ctx, params, data) {<br>    return new Promise(async (resolve, reject) =&gt; {<br><br>      const [error, result] = await to(DB.insert(ctx.tenant, COLLECTION, data))<br><br>      if (error) {<br>        return resolve({error})<br>      }<br><br>      resolve(result)<br>    })<br>  }<br><br>  static find (ctx, params, query) {<br>    return new Promise(async (resolve, reject) =&gt; {<br>      const [error, processes] = await to(DB.find(ctx.tenant, COLLECTION))<br>      if (error) {<br>        return resolve({error})<br>      }<br>      return resolve(processes)<br>    })<br>  }<br>}<br><br>module.exports = Task</pre><p>We will make changes to the application startup to initialize the connection manager</p><p>Add the lines below to app.js just above the line const app = new Koa()</p><pre>const mongoOpts = {<br>  host: config.mongo.host,<br>  max: 5,<br>  min: 1,<br>  timeout: 30000,<br>  logout: false<br>}<br><br>// init the connection pool<br>require(&#39;./db/connectionMgr&#39;).init(mongoOpts)</pre><p>We need a middleware to set tenants to context, add the middleware code after const app = new Koa()</p><pre>async function setTenant (ctx, next) {<br>  const domain = ctx.subdomains[4]<br>  ctx.tenant = domain || &#39;default&#39;<br>  await next()<br>}<br><br>app.use(setTenant)</pre><p>We will be using xip.io to set subdomains in our requests, more about this a bit later.</p><p>Let us now complete the task service, replace service/v1/tasks.js with code given below</p><pre>&#39;use strict&#39;<br>const koaBody = require(&#39;koa-body&#39;)()<br>const to = require(&#39;await-to-js&#39;).default<br>const Task = require(&#39;../../models/task&#39;)<br><br>const create = async function (ctx, next) {<br>  ctx.status = 201<br><br>  const [error, result] = await<br>                  to(Task.create(ctx, ctx.params, ctx.request.body))<br><br>  if (error || result.error) {<br>    ctx.status = 400<br>    ctx.body = error || result.error<br>  } else {<br>    ctx.body = result<br>  }<br><br>  return next()<br>}<br><br>const find = async function (ctx, next) {<br>  ctx.status = 200<br>  const [error, result] = await to(Task.find(ctx, ctx.params, ctx.query))<br><br>  if (error || result.error) {<br>    ctx.status = 400<br>    ctx.body = error || result.error<br>  } else {<br>    ctx.body = result<br>  }<br><br>  return next()<br>}<br><br>exports.register = (router) =&gt; {<br>  // POST api/v1/tasks<br>  router.post(&#39;/tasks&#39;, koaBody, create)<br><br>  // GET api/v1/tasks<br>  router.get(&#39;/tasks&#39;, find)<br>}</pre><p>Before we test the application we need to install some more modules, let us install mongodb (native driver) and lodash. Also ensure, your mongodb is up and running.</p><pre>npm i -S mongodb lodash await-to-js</pre><p>A quick word about await-to-js module. The module is very helpful async await style of coding by removing the need for wrapping the calls in a try catch block. More information can be found in the blog [<a href="http://blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/">http://blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/</a>]</p><p>To test the code, try to find your ip address using ifconfig assuming it is 10.0.0.3, you can use the service xip.io to access your machine using the url <a href="http://10.0.0.3.xip.io/">http://10.0.0.3.xip.io</a></p><p>To simulate multi domain access try the application using url</p><ul><li><a href="http://alpha/">http://alpha</a>.&lt;your_ip&gt;.xip.io:3000 and</li><li><a href="http://beta/">http://beta</a>.&lt;your_ip&gt;.xip.io:3000</li></ul><p>Once again, use curl / postman to try out the post methods as well.</p><p>We have made a quick introduction to multi-tenancy and implemented a partially shared model with application layer shared and database not shared. The code even though functional, is far from a production grade code. I hope people can use this model to build further.</p><p>If you have followed this far, thanks a lot for your time. Please let me know what you think it will help me improve further.</p><p>Github Repository: [<a href="https://github.com/harin76/multi-tenant-example">https://github.com/harin76/multi-tenant-example</a>]</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b09df372128" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>