<?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 Ridermansb on Medium]]></title>
        <description><![CDATA[Stories by Ridermansb on Medium]]></description>
        <link>https://medium.com/@ridermansb?source=rss-fe49a771c747------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AqLMS3JhppA2pI6RawBnYw.jpeg</url>
            <title>Stories by Ridermansb on Medium</title>
            <link>https://medium.com/@ridermansb?source=rss-fe49a771c747------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 06:52:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ridermansb/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[Web PushNotification made simple with webtask.io]]></title>
            <link>https://medium.com/@ridermansb/web-pushnotification-made-simple-with-webtask-io-4cb4a21d274?source=rss-fe49a771c747------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cb4a21d274</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[auth0]]></category>
            <category><![CDATA[web-push-notifications]]></category>
            <category><![CDATA[webtask]]></category>
            <dc:creator><![CDATA[Ridermansb]]></dc:creator>
            <pubDate>Sun, 22 Oct 2017 19:19:43 GMT</pubDate>
            <atom:updated>2017-10-25T11:33:36.866Z</atom:updated>
            <content:encoded><![CDATA[<p>You don’t need too much to implement a push notification for your web app. Actually is pretty simple, just follow three steps.</p><ol><li>Ask permission for the user</li><li>Subscribe the user saving his keys into a database</li><li>Create ServiceWorker that will listening for notifications and display-it</li></ol><p>After that, you use this keys to send a push notification.<br>You don’t need anything spectacular, no external service or API to do that.</p><p>In this post, I will explain how can we archive this without any database, just HTML/JS and <a href="https://webtask.io/">WebTask.io.</a></p><p>You can find the source code on GitHub: <a href="https://github.com/Ridermansb/push-notification-when-webhook">https://github.com/Ridermansb/push-notification-when-webhook</a></p><h3>Asking user permission</h3><p>First task is ask the user permission to send push notification, this can be done by using <a href="https://developer.mozilla.org/en-US/docs/Web/API/notification">Notification API</a></p><pre><em>const </em>status = <em>await </em>Notification.requestPermission();</pre><p>This code will prompt the user if the current webpage can send push notification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*_A5GFQ3tJMc_rfNAQ8niuw.png" /><figcaption>Asking user permission to send push notification</figcaption></figure><p>Once the user accept, you need to generate a subscription and save-it to the database, to archive this we need a API and an way to store the subscription.</p><h3>Create Webtask.io to handle our API and Storage</h3><p><a href="https://webtask.io/">Webtask.io</a> works as FaaS, you can create functions that will work as endpoints. Make serverless endpoints.</p><p>Create new file called `hook.js` with</p><pre><em>const </em>webPush = require(&#39;web-push&#39;);<br><em>const </em>Webtask = require(&#39;webtask-tools&#39;);<br><em>const </em>app = <em>new </em>(require(&#39;express&#39;))();<br><em>const </em>bodyParser = require(&#39;body-parser&#39;);<br><br>app.use(bodyParser.json());<br>app.use(bodyParser.urlencoded({<br>    extended: <em>true</em>,<br>}));<br><br>webPush.setVapidDetails(<br>    &#39;mailto:your@email.com&#39;,<br>    process.env.VAPID_PUBLIC,<br>    process.env.VAPID_PRIVATE<br>);</pre><pre>app.post(&#39;/hook&#39;, (req, res) =&gt; {<br>  // Will fired by WebHook<br>})</pre><pre>app.post(&#39;/subscribe&#39;, (req, res) =&gt; {<br>  // Will fired when user accept push notification <br>})</pre><p>This is a very simple express app with two endpoints<br>The first one /hook will fired by webhook and push to the all subscription, the second one `/subscribe` will save the subscriptions.</p><p>The <strong>VAPID_PUBLIC</strong> and <strong>VAPID_PRIVATE</strong> can be retreived by <a href="https://www.npmjs.com/package/web-push">WebPush library</a> using command line bellow:</p><pre>web-push generate-vapid-keys</pre><h4>Implement subscribe functionality</h4><p>Subscribe endpoint will only save the keys, to do that we can use <a href="https://webtask.io/docs/webtask_storage">Webtask Storage</a> feature, a micro storage that uses JSON file.</p><pre>app.post(&#39;/subscribe&#39;, (req, res) =&gt; {<br>    <em>const </em>{ storage } = req.webtaskContext;<br>    <em>const </em>{ endpoint, keys } = req.body;<br><br>    storage.get((errorGet, data) =&gt; {<br>        <em>if </em>(errorGet) { <em>return </em>res.send(400); }<br>        <em>if </em>(!data) {<br>            data = { subscriptions: [] }<br>        }<br><br>        data.subscriptions.push({<br>            titleField: <em>false</em>,<br>            bodyField: <em>false</em>,<br>            sub: {<br>                endpoint,<br>                keys: { p256dh: keys.p256dh, auth: keys.auth },<br>            }<br>        });<br>        storage.set(data, <em>function</em>() {<br>            <em>return </em>res.status(200).json({ ok: <em>true </em>})<br>        });<br>    })<br>});</pre><h4>Implement push functionality</h4><p>Here we need implement a hook that will trigger the push notification. All we need to do is:</p><ol><li>Lookup all subscription</li><li>Send push notifications to these subscriptions</li></ol><pre>app.post(&#39;/hook&#39;, (req, res) =&gt; {<br>    <em>const </em>{ storage } = req.webtaskContext;<br><br>    storage.get((error, data) =&gt; {<br>        <em>if </em>(error) { <em>return </em>res.send(400); }<br>        <em>if </em>(!data) {<br>            data = { subscriptions: [] }<br>        }</pre><pre>        <em>const </em>payload = JSON.stringify({<br>            title: &#39;Hook trigger&#39;,<br>            body: &#39;New hook trigger&#39;,<br>        });<br><br>        <em>const </em>sendPushPromises = data.subscriptions<br>            .map(data =&gt; {<br>                webPush.sendNotification(data.sub, payload, { TTL: 3600 })<br>            });<br>        Promise.all(sendPushPromises)<br>            .then(resp =&gt; res.json(resp))<br>            .catch(e =&gt; res.send(400));<br>    });<br>});</pre><p>That’s all we need to do in our Webtask, now we need save the subscription once the user accept. Let’s replace your request Permission code (UI)</p><pre><em>const </em>status = <em>await </em>Notification.requestPermission()<br><em>if </em>(status === &#39;granted&#39;) {<br>    <em>await this</em>.saveSubscription()<br>}</pre><p>And save the subscription</p><pre><em>async </em>saveSubscription() {<br>    <em>const </em>reg = <em>await </em>navigator.serviceWorker.ready;<br>    <em>const </em>sub = <em>await </em>reg.pushManager.subscribe({<br>        userVisibleOnly: <em>true</em>,<br>        applicationServerKey: urlB64ToUint8Array(VAPID_PUBLIC),<br>    });<br><br>    subscribe(sub); // Call API with post method<br>}</pre><p>So far so good. The last step is listening for notifications</p><h3>ServiceWorker that listening for notifications</h3><p>The way that push notifications works, even if you close the browser, is because you have a Service worker that is running in background.</p><p>With service worker, we can keep our app running listening for notifications . Just create a new file called sw.js with :</p><pre>self.addEventListener(&#39;push&#39;, (event) =&gt; {    <br>  const notificationData = event.data.json();     <br>  event.waitUntil(<br>    self.registration.showNotification(<br>      notificationData.title, {<br>        body: notificationData.body,<br>        icon: notificationData.icon, <br>        tag: notificationData.tag,<br>      }),<br>    );<br>  }<br>);</pre><p>This will listening the push events and display notification when the event is fired.</p><p>To register this service worker, just install-it</p><pre>// Register Service worker<br>if (&#39;serviceWorker&#39; in navigator) {<br>    navigator.serviceWorker.register(&#39;./sw.js&#39;, { scope: &#39;/&#39; });}<br>else {<br>    console.warn(&#39;Not supported by browser&#39;);<br>}</pre><h3>Publishing our WebTask</h3><p>Our first webtask is ready, to create and publish please install the <a href="https://webtask.io/cli">Webtask CLI</a> and execute the follow command.</p><pre><em>wt create hook.js --name myhook -d web-push</em></pre><p>This command will create new webtask and return the URL that will be used as API.</p><p>Now you only need to put the URL &quot;https://&lt;WEB_TASK_URL&gt;/hook&quot; to your hook and see the magic happens</p><p>You can find a <a href="https://push-notification-when-webhook.ridermansb.me/">live demonstration here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cb4a21d274" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Update your web app version dynamically with git-describe]]></title>
            <link>https://medium.com/bind-solution/dynamic-version-update-with-git-describe-477e8cd2a306?source=rss-fe49a771c747------2</link>
            <guid isPermaLink="false">https://medium.com/p/477e8cd2a306</guid>
            <category><![CDATA[webpack-2]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Ridermansb]]></dc:creator>
            <pubDate>Sat, 03 Jun 2017 03:27:05 GMT</pubDate>
            <atom:updated>2017-06-03T04:33:37.868Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*udcQCmgPFTFhHV2I1ucCJg.png" /></figure><p>Git tags help you to mark a point in your git history, we use this to mark our code/software version.</p><h3>A little more about tags</h3><p>In git we have two &quot;kinds&quot; of tags .</p><p><strong>Annotated tag — </strong>Is store with some information</p><pre>git tag -a v1.0 -m &quot;First version&quot;</pre><p><strong>Lightweight — </strong>Is an simple commit checksum without any extra information</p><pre>git tag v1.0</pre><p>This is important because `git description`treats this “kind”of tags different.</p><h3>Git-describe</h3><p><a href="https://www.git-scm.com/docs/git-describe">git describe</a> is a git command that display the last reachable tag , this can be useful if you want to know the exact version of your code.</p><p>In your CI for instance, if fail you want to know what was the exact version of your code that failed.</p><h4>Let’s do to understand</h4><p>Let&#39;s build a very simple calculator.</p><pre>❯ yarn init . &amp;&amp; yarn add assert -D &amp;&amp; git init .</pre><p>Our first version will sum two numbers</p><pre>// calc.test.js<br><strong>const </strong>assert = require(&#39;assert&#39;);<br><strong>const </strong>calc = require(&#39;./calc&#39;);<br>assert.equal(calc.sum(1,1), 2);</pre><pre>// calc.js<br>module.<strong>exports </strong>= {<br>  <strong>sum</strong>: (n1, n2) =&gt; n1 + n2<br>}</pre><p>Our first commit will be like this</p><pre>❯ git add . &amp;&amp; git commit -am &quot;Sum feature&quot;</pre><p>If we execute `git describe` the result will be..</p><pre>❯ git describe <br>fatal: No names found, cannot describe anything.</pre><p>The reason is because there are nothing to describe, in this moment we don&#39;t have any tag just commits.</p><p>The documentation said that.</p><blockquote>Describe a commit using the <strong>most recent tag reachable</strong> from it</blockquote><p>So let&#39;s add an tag for our version</p><pre>❯ git tag v1.0.0</pre><p>As mention before, there are two kinds of tags, annotated and unannotated. The command above just create an unannotated tag.</p><p>There reason this is important is because git describe, by default, only shows annotated tags</p><pre>❯ git describe <br>fatal: No annotated tags can describe ‘544a96f6fb66dcb858df2ec0172def47430297dc’.<br>However, there were unannotated tags: try — tags.</pre><blockquote>By default (without — all or — tags) git describe only shows annotated tags.</blockquote><p>We can see our most recent tag using ` — tags` flag</p><pre>❯ git describe — tags <br>v1.0.0</pre><p>But this not helps us if our CI fail and we need to check the exact version that failed. Let’s try instead use unannotated tags, use more descriptive (annotated) tags.</p><h4>Adding subtract feature</h4><pre>// calc.test.js<br>assert.equal(<strong>calc</strong>.sub(10,5), 5);</pre><pre>// calc.js<br>sub: (n1, n2) =&gt; n1 - n2</pre><p>And publish our app with version 1.1.0</p><pre>❯ git add . &amp;&amp; git commit -am &quot;Add sub feature&quot;<br>❯ git tag -a v1.1.0 -m &quot;Subtract feature&quot;</pre><p>Now we have two tags `v1.0.0` with sum feature and `v1.1.0` with subtract feature.</p><pre>❯ git tag <br>v1.0.0<br>v1.1.0</pre><p>As we annotated our last tag, the `git describe` will <strong>show the most recent annotated tag.</strong></p><pre>❯ git describe <br>v1.1.0</pre><blockquote>The command finds the <strong>most recent tag that is reachable</strong> from a commit. If the tag points to the commit, then only the tag is shown.</blockquote><p>Until now we have a publish 1.1.0 version of our app with sum and subtract feature.</p><p>But, what&#39;s happen if we keep changing our code and don&#39;t put any tag?</p><h4>Adding multiply feature</h4><pre>// calc.test.js<br>assert.equal(<strong>calc</strong>.mult(5,5), 25);</pre><pre>// calc.js<br>mult: (n1, n2) =&gt; n1 * n2</pre><p>This time we will not publish a new tag(version), we simple commit the code</p><pre>git add . &amp;&amp; git commit -am &quot;Add multiply feature&quot;</pre><p>The trick here is, we are no longer on version `1.1.0` , <strong>we are ahead of this version</strong>, if the test fails all information that we have is the git hash. Is when describe feature comes to handy.</p><pre>❯ git describe<br>v1.1.0–1-g831f2d6</pre><p>Let&#39;s split this ..</p><ul><li><strong>v1.1.0</strong> — Is the last tag</li><li><strong>1</strong> — Is how many commits we area ahead</li><li><strong>g</strong> — Stands for “git” and is used to allow describing the version of a software depending on the SCM the software is managed with.</li><li><strong>831f2d6</strong> — 7-char abbreviation for the tip commit of parent</li></ul><p>Now describe can be useful, in our CI we know the exactly version and commit that fail.</p><p>We can keep adding features..</p><pre>// calc.test.js<br>assert.equal(<strong>calc</strong>.div(10,2), 5);</pre><pre>// calc.js<br>div: (n1, n2) =&gt; n1 / n2</pre><p>The git describe will be..</p><pre>❯ git add . &amp;&amp; git commit -am &quot;Add divider feature&quot;<br>❯ git describe                 <br>v1.1.0-2-gdc8528b</pre><p><strong>2 </strong>because we are 2 commits ahead of the last tag, and <strong>dc8528b </strong>as<strong> </strong>7-char abbreviation for the tip commit.</p><p>As you can see, is more descriptive way to display the exactly version of your code.</p><h3>Use git-describe to manager our app version</h3><p>git describe helps you to identify the exact version of your code, and we can use this to automatic display the app version.</p><h4>Let’s do to understand</h4><p>Let&#39;s build a web app that use our calc.js module. To do this we will use webpack in order generate our bundle and HTML.</p><pre>❯ yarn add webpack html-webpack-plugin -D</pre><p>And configure</p><pre>// webpack.config.js</pre><pre><strong>const </strong>path = require(&#39;path&#39;);<br><strong>const </strong>HtmlWebpackPlugin = require(&#39;html-webpack-plugin&#39;);<br><br>module.exports = {<br>  <strong>entry</strong>: &#39;./app.js&#39;,<br>  <strong>output</strong>: {<br>    <strong>path</strong>: path.resolve(__dirname, &#39;dist&#39;),<br>    <strong>filename</strong>: &#39;app.js&#39;,<br>  },<br>  <strong>plugins</strong>: [<strong>new </strong>HtmlWebpackPlugin({<br>      <strong>title</strong>: &#39;Calculator&#39;,<br>      <strong>template</strong>: &#39;index.ejs&#39;,<br>    })<br>  ]<br>};</pre><pre>-----</pre><pre>// app.js</pre><pre><strong>const calc </strong>= require(&#39;./calc&#39;);<br><br><strong>const </strong>n1El = <strong>document</strong>.getElementById(&#39;n1&#39;);<br><strong>const </strong>n2El = <strong>document</strong>.getElementById(&#39;n2&#39;);<br><strong>const </strong>resultEl = <strong>document</strong>.getElementById(&#39;result&#39;);<br><br><strong>const </strong>execOperation = (operation) =&gt; {<br>  <strong>const </strong>n1 = parseInt(n1El.value);<br>  <strong>const </strong>n2 = parseInt(n2El.value);<br>  resultEl.<strong>textContent </strong>= operation(n1, n2);<br>}<br><strong>const </strong>applyOperation = (elementId, operation) =&gt; {<br>  <strong>document<br>    </strong>.getElementById(elementId)<br>    .addEventListener(&quot;click&quot;, <strong>function</strong>() {<br>      execOperation(operation)<br>    });<br>}<br>applyOperation(&quot;sumBtn&quot;, <strong>calc</strong>.sum);<br>applyOperation(&quot;subBtn&quot;, <strong>calc</strong>.sub);<br>applyOperation(&quot;multBtn&quot;, <strong>calc</strong>.mult);<br>applyOperation(&quot;divBtn&quot;, <strong>calc</strong>.div);</pre><pre>-------</pre><pre>// index.ejs</pre><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;title&gt;&lt;%= htmlWebpackPlugin.options.<strong>title </strong>%&gt;&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;label for=<strong>&quot;n1&quot;</strong>&gt;<strong>N1</strong>&lt;/label&gt;&lt;input type=<strong>&quot;number&quot; </strong>id=<strong>&quot;n1&quot; </strong>/&gt;<br>    &lt;label for=<strong>&quot;n2&quot;</strong>&gt;<strong>N2</strong>&lt;/label&gt;&lt;input type=<strong>&quot;number&quot; </strong>id=<strong>&quot;n2&quot; </strong>/&gt;<br>    &lt;button id=<strong>&quot;sumBtn&quot;</strong>&gt;<strong>+</strong>&lt;/button&gt;<br>    &lt;button id=<strong>&quot;subBtn&quot;</strong>&gt;<strong>-</strong>&lt;/button&gt;<br>    &lt;button id=<strong>&quot;multBtn&quot;</strong>&gt;<strong>*</strong>&lt;/button&gt;<br>    &lt;button id=<strong>&quot;divBtn&quot;</strong>&gt;<strong>/</strong>&lt;/button&gt;<br>    <strong>= </strong>&lt;span id=<strong>&quot;result&quot;</strong>&gt;&lt;/span&gt;<br>    &lt;hr&gt;<br>    &lt;footer&gt;<br>        &lt;span id=<strong>&quot;version&quot;</strong>&gt;&lt;/span&gt;<br>    &lt;/footer&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Run webpack will generate in dist folder our index.html with script tag point to app.js .</p><p>And our `index.html` on browser will be like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*cW-U_bxRvrDYhhPwbnqWNQ.png" /></figure><blockquote>The question here is how to add git describe version in our html on tag #version.</blockquote><p>To archive this we need to use the <a href="https://www.npmjs.com/package/git-revision-webpack-plugin">git-revision-webpack-plugin</a>.</p><pre>yarn add git-revision-webpack-plugin -D</pre><p>This is a very simple and useful plugin that use git describe to get our code version and allow us to use it our webpack configuration.</p><p>We can use this in conjunction with <a href="https://webpack.js.org/plugins/define-plugin/">DefinePlugin</a> to &quot;export&quot; our version to HTML.</p><h4>Let&#39;s do it</h4><p>First change the &#39;webpack.config.js&#39; as follow</p><pre><strong>// </strong>Add<strong> ..</strong></pre><pre><strong>const </strong>webpack = require(&#39;webpack&#39;);<br><strong>const </strong>GitRevisionPlugin = require(&#39;git-revision-webpack-plugin&#39;);<br><strong>const </strong>gitRevisionPlugin = <strong>new </strong>GitRevisionPlugin();<br>...</pre><pre>// And in plugins<br>plugins: [<br>  ...<br>  <strong>new </strong>webpack.DefinePlugin({<br>    &#39;VERSION&#39;: <strong>JSON</strong>.stringify(gitRevisionPlugin.version()),<br>    &#39;COMMITHASH&#39;: <strong>JSON</strong>.stringify(gitRevisionPlugin.commithash()),<br>    &#39;BRANCH&#39;: <strong>JSON</strong>.stringify(gitRevisionPlugin.branch()),<br>  })<br>]</pre><p>Now in our app.js we have access to these variables, we can simple change the version.</p><pre><strong>const </strong>versionEl = <strong>document</strong>.getElementById(&#39;version&#39;);<br><br>versionEl.<strong>textContent </strong>= `VERSION: &quot;${VERSION}&quot; COMMITHASH: &quot;${COMMITHASH}&quot; BRANCH: &quot;${BRANCH}&quot;`;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mq-HyFIJgxAxdLYyii_aCA.png" /><figcaption>Calculator with version from git</figcaption></figure><p>And after publish a new version.</p><pre>❯ git add . &amp;&amp; git commit -am &quot;Add web interface&quot;<br>❯ git tag -a v1.2.0 -m &quot;Add web interface to access the calculator features&quot;</pre><p>Our describe will display the current version.</p><pre>❯ git describe <br>v1.2.0</pre><p>And our interface will display the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gxi9et7TDS_rf3PXuIqUKQ.png" /></figure><h4>Conclusion</h4><p>As demonstrated git-describe can be use to identify our code in CI or display version in our app.</p><p>Check my <a href="https://github.com/Ridermansb/dynamic-app-version-update">github repository with the full code</a>.</p><blockquote><em>Like this? Please click ❤️ bellow so other people can find it.</em></blockquote><h4>Reference</h4><ul><li><a href="http://alblue.bandlem.com/2011/04/git-tip-of-week-tags.html">Git Tip of the Week: Tags</a></li><li><a href="https://www.git-scm.com/docs/git-describe">Git - git-describe Documentation</a></li><li><a href="https://wildlyinaccurate.com/a-hackers-guide-to-git/#git-reflog">A Hacker&#39;s Guide to Git | Wildly Inaccurate</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=477e8cd2a306" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bind-solution/dynamic-version-update-with-git-describe-477e8cd2a306">Update your web app version dynamically with git-describe</a> was originally published in <a href="https://medium.com/bind-solution">Bind Solution</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Add multiples SSH keys on the same host]]></title>
            <link>https://medium.com/@ridermansb/add-multiples-ssh-keys-on-the-same-host-daced623f859?source=rss-fe49a771c747------2</link>
            <guid isPermaLink="false">https://medium.com/p/daced623f859</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[bitbucket]]></category>
            <category><![CDATA[ssh]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Ridermansb]]></dc:creator>
            <pubDate>Sun, 28 May 2017 07:37:33 GMT</pubDate>
            <atom:updated>2017-06-11T21:39:35.131Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qw8JJWA9H0GSWZko1zO8vw.jpeg" /></figure><p>This is a case if you use the same machine for work/home. You will need to be able to use different keys for different host.</p><p>One for <strong>git@mywork.com/project.git</strong></p><p>One for <strong>git@github.com/project.git</strong></p><p>Assuming that you already use id_rsa key for your github.com all we need is tell to ssh-agent to use the other key when the host is mywork.com</p><p>First, create a key for your work key</p><h3>Creating new key</h3><pre><strong>$ ssh-keygen -t rsa -C &quot;your@work.email&quot; -f &quot;id_rsa_WORK&quot;<br># Your identification has been saved in id_rsa_WORK_rsa.<br>Your public key has been saved in id_rsa_WORK_rsa.pub.<br>The key fingerprint is:<br>XXX<br>The key&#39;s randomart image is:<br>+--[ RSA 2048]----+<br>|                 |<br>|                 |<br>|                 |<br>+-----------------+</strong></pre><p>This will generate <strong>id_rsa_WORK </strong>in your .ssh folder.</p><p>Ensure ssh-agent is enabled:</p><pre><strong>$ eval &quot;$(ssh-agent -s)&quot;<br># Agent pid 59566</strong></pre><p>And we need to tell the agent about our new key</p><pre><strong>$ ssh-add ~/.ssh/id_rsa_WORK<br># Identity added: id_rsa_WORK (id_rsa_WORK)</strong></pre><h3>Configure per host</h3><p>When you clone/push an git repo from work, you use an uri like <strong>git@mywork.com/project.git , </strong>we need to tell the agent that when we use this host mywork.com to use a different key.</p><p>This is done adding into the .ssh/config file</p><pre><strong>Host mywork.com<br>    HostName mywork.com<br>    User git<br>    IdentityFile ~/.ssh/id_rsa_OTHERUSER</strong></pre><h3>Setting user</h3><p>For the last, we need to change the user for the local repo.</p><p>So after clone the repository, set your work user</p><pre><strong>git config user.name &quot;work_username&quot;<br>git config user.email &quot;me@work.com&quot;</strong></pre><p>As we don&#39;t user global option, so this configuration will be placed in local repository only.</p><p>You can test the new key using `ssh -v git@mywork.com`</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=daced623f859" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a MQTT server using Functional Programming paradigm]]></title>
            <link>https://medium.com/@ridermansb/create-a-mqtt-server-using-functional-programming-paradigm-145e97a3298f?source=rss-fe49a771c747------2</link>
            <guid isPermaLink="false">https://medium.com/p/145e97a3298f</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[mqtt]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[ramda]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ridermansb]]></dc:creator>
            <pubDate>Sun, 28 May 2017 04:28:47 GMT</pubDate>
            <atom:updated>2017-05-28T07:50:01.861Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tEuqlRbCNOP6kMd7W5j3pw.jpeg" /></figure><p>We have severals libraries to help us with routes and redirect the request for the right function (aka controller) in http servers, but and about MQTT?</p><p>In MQTT we receive an topic with payload and we should be able to figure out whats this request is about and handle this request with the right function.</p><pre>server.on(&#39;published&#39;, (packet, client, cb) =&gt; {<br>  // Whats to <strong>do</strong> with the package ?<br>});</pre><p>The question that I will try to answer is how handle MQTT request with functional programming paradigm.</p><h3>The processor</h3><p>The first step is create a module that process the request ..</p><pre>server.on(&#39;published&#39;, (packet) =&gt; {<br>  processor(packet);<br>});</pre><p>The processor will figure out what the packet is about and redirect to the right handler.</p><pre>// processor.js<br><strong>export</strong> <strong>default</strong> <strong>function</strong> <strong>processor</strong>(packet, client) {<br>  <strong>const</strong> resolve = R.cond([<br>    [COND, EXEC]<br>  ]);<br>  resolve(packet);<br>}</pre><p>The idea is simple, <strong>COND</strong> is a function that return true or false , if truethe <strong>EXEC</strong> function will be executed. See more about <a href="http://ramdajs.com/docs/#cond">R.cond in Ramda docs</a>.</p><p>resolve is a function that will return whatever <strong>EXEC</strong> return</p><p>So, for example ..</p><pre><strong>const</strong> paket = {<br>  topic: &#39;world&#39;<br>}</pre><pre><strong>const</strong> resolve = R.cond([<br>  [() =&gt; <strong>true</strong>, (p) =&gt; &#39;hello &#39; + p.topic]<br>]);</pre><pre>resolve(packet); // hello world</pre><p>As you can see, is a array of arrays, so we can have multiples conditions..</p><pre><strong>const</strong> resolve = R.cond([<br>  [() =&gt; <strong>true</strong>, (p) =&gt; &#39;hello &#39; + p.topic],<br>  [OTHER_FN, OTHER_EXEC],<br>  [ONE_MORE_FN, ONE_MORE_EXEC],<br>  // ...<br>]);</pre><h3>The request</h3><p>Using this approach we can handle request very easier, all we need to do is create javascript modules as follow..</p><pre>// processRequestExample.js<br>export function <strong>execute</strong>(packet) {<br>  // Process packet <strong>and</strong> <strong>return</strong> a valida packet <strong>or</strong> null<br>}<br><strong>export</strong> <strong>function</strong> <strong>match</strong>(packet) {<br>  // <strong>Return</strong> true <strong>if</strong> <strong>execute</strong> should be <strong>execute</strong><br>}<br><strong>export</strong> <strong>default</strong> [<strong>match</strong>, <strong>execute</strong>];</pre><p>And import this module on processor.js</p><pre><strong>import</strong> processRequestExample <strong>from</strong> &#39;./processRequestExample&#39;<br><strong>const</strong> resolve = R.cond([<br>  processRequestExample<br>]);</pre><h3>The publish</h3><p>For last but not less import, if our resolve return an packet we need to publish the response. Let&#39;s change our processor.js ..</p><pre><strong>export</strong> <strong>default</strong> <strong>function</strong> <strong>processor</strong>(packet, publish) {<br>  <strong>const</strong> resolve = R.cond([<br>    processRequestExample,<br>  ]);</pre><pre>  <strong>const</strong> publishIfConditionalResolved = R.pipe(<br>    resolve,<br>    R.when(R.identity, publish),<br>  );</pre><pre>  publishIfConditionalResolved(packet);<br>}</pre><blockquote><em>R.when resolve the second function if the first one return true.</em></blockquote><blockquote><em>In this case, if </em><em>resolve return a value, </em><em>publish will be called with this value.</em></blockquote><p>And our server,</p><pre>server.on(&#39;published&#39;, (packet, client, cb) =&gt; {<br>  const onPublish = (packetResp) =&gt; {<br>    server.publish(packetResp, client, cb);<br>  };<br>  processor(packet, onPublish);<br>});</pre><p>This makes easier handle MQTT request and answer this request if necessary.</p><h3>More real situation</h3><p>Let’s create an sum calculator, will be able to sum two numbers from topic,</p><ul><li>When receive a packet from topic calc/{num1},{num2}</li><li>With the payload { &quot;command&quot;: &quot;sum&quot; }</li><li>Should return {result} with sum of {num1} + {num2}</li></ul><h3>#1 Add handle to our processor</h3><pre><strong>import</strong> sumCalc <strong>from</strong> &#39;./sumCalc&#39;;</pre><pre><strong>export</strong> <strong>default</strong> <strong>function</strong> <strong>processor</strong>(packet, publish) {<br>  <strong>const</strong> resolve = R.cond([<br>    sumCalc<br>  ]);</pre><pre>  // ...<br>}</pre><h3>#2 Implement sumCalc</h3><p>We have to figure out if the request should be resolve by our module match and if so we need extract and sum the numbers from the topic.</p><h4>match function</h4><p>The match function job is answer true if the packet should be resolve by this module or false if not.</p><p>To do that, we need validate the topic and payload</p><ul><li>To validate the topic, we can use an simple regex</li><li>To validate the payload we can use <a href="https://github.com/epoberezkin/ajv">ajv</a> that validate the payload against JSON schema.</li></ul><p>I will comment the code to make easier to understand</p><pre>// Topic regex validator<br><strong>const</strong> matchChannel = /^calc\/(\d+)\,(\d+)/im;</pre><pre>// JSON Schema validator<br><strong>const</strong> ajv = <strong>new</strong> Ajv();<br><strong>const</strong> payloadRequestValidator = ajv.compile({<br>  type: &#39;object&#39;,<br>  properties: {<br>    command: {<br>      type: &#39;string&#39;,<br>      pattern: &#39;^sum$&#39;,<br>    },<br>  },<br>  required: [&#39;command&#39;],<br>});</pre><pre><strong>export</strong> <strong>function</strong> <strong>match</strong>() {<br>  // Validate topic against regex<br>  <strong>const</strong> topicLens = R.lensProp(&#39;topic&#39;);<br>  <strong>const</strong> isTopicValid = R.pipe(R.view(topicLens), R.test(matchChannel));</pre><pre>  // Get JSON<br>  <strong>const</strong> payloadLeans = R.lensProp(&#39;payload&#39;);<br>  <strong>const</strong> payloadView = R.view(payloadLeans);<br>  <strong>const</strong> utf8String = prop =&gt; prop.toString(&#39;utf-8&#39;);<br>  <strong>const</strong> getPayload = R.pipe(R.over(payloadLeans, utf8String), payloadView, JSON.parse);</pre><pre>  // Check JSON schema<br>  <strong>const</strong> isPayloadValid = R.pipe(R.tryCatch(getPayload, R.F), payloadRequestValidator);</pre><pre>  // If is a valid schema and valid topic, return true<br>  <strong>return</strong> R.both(isPayloadValid, isTopicValid);<br>}</pre><blockquote><em>A lot of Ramda commands here, please check the docs for better understand :) </em><a href="https://hashnode.com/util/redirect?url=http://ramdajs.com/docs/"><em>ramdajs.com/docs</em></a></blockquote><h4>execute function</h4><p>Now we need implement the execute function that should</p><ol><li>Extract n1 and n2 from topic</li><li>Sum numbers</li><li>Return a packet with result</li></ol><pre><strong>export</strong> <strong>function</strong> <strong>execute</strong>() {<br>  // Used to extract numbers<br>  <strong>const</strong> matchNumbers = R.match(matchChannel);<br>  <strong>const</strong> topicProp = R.lensProp(&#39;topic&#39;);<br>  <strong>const</strong> viewTopic = R.view(topicProp);<br>  <strong>const</strong> transformToBuffer = obj =&gt; <strong>new</strong> Buffer.from(JSON.stringify(obj));</pre><pre>  // Convert property n1 and n2 to int<br>  <strong>const</strong> transformations = { n1: parseInt, n2: parseInt };<br>  <strong>const</strong> extractAndSum = R.pipe( // #1<br>    viewTopic,<br>    matchNumbers,<br>    R.zipObj([&#39;all&#39;, &#39;n1&#39;, &#39;n2&#39;]),<br>    R.pick([&#39;n1&#39;, &#39;n2&#39;]),<br>    R.evolve(transformations),<br>    R.values,<br>    R.sum,<br>    transformToBuffer<br>  );</pre><pre>  <strong>const</strong> payloadProp = R.lensProp(&#39;payload&#39;);<br>  <strong>const</strong> setPayload = R.set(payloadProp);<br>  <strong>return</strong> R.chain(setPayload, extractAndSum);<br>}</pre><p>If you pay attention on #1 we ..</p><ol><li>Get the topic value in viewTopic</li><li>Extract numbers using regex in matchNumbers</li><li>Regex return an array like [&#39;calc/2,3&#39;, &#39;2&#39;, &#39;5&#39;] , so we convert to a object {all: &#39;calc/2,3&#39;, n1: &#39;2&#39;, n2: &#39;5&#39;} in zipObj</li><li>Return a object with n1 and n2 only in pick</li><li>Transform properties n1 and n2 using transformations in evolve</li><li>Return array with the values only, {n1: 2, n2: 5} will be [2,5] in values</li><li>Sum the array in sum</li><li>Convert to buffer result in transformToBuffer</li></ol><h4>Export default</h4><p>You should be notice that match and execute don&#39;t have any params, the reason is because we don&#39;t need, we can export with R.call</p><pre><strong>export</strong> <strong>default</strong> [R.call(match), R.call(execute)];</pre><p>You can find the <a href="https://github.com/Ridermansb/mqtt-server-fp-style">full code on my github</a>.</p><p>Feel free to ask me any question. :)</p><blockquote>Like this? Please click ❤️ bellow so other people can find it.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=145e97a3298f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Promise state with React+Mobx]]></title>
            <link>https://medium.com/@ridermansb/promise-state-with-react-mobx-86ab4054f43c?source=rss-fe49a771c747------2</link>
            <guid isPermaLink="false">https://medium.com/p/86ab4054f43c</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[mobx]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Ridermansb]]></dc:creator>
            <pubDate>Sun, 28 May 2017 04:02:37 GMT</pubDate>
            <atom:updated>2017-05-28T07:56:01.338Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*14DxAujaCZ9xNNoJU8VS9Q.jpeg" /></figure><p>I&#39;m pretty sure that you end up with a situation when your component need to fetch data from the database and this process envolve</p><ul><li>Display loading status</li><li>Display error if the promise is rejected</li><li>Update data if the promise is resolved</li></ul><p>Whats is the effective way manage this states isLoading , error in react? <br>Sounds like a simple answer, so ..</p><h3>Let’s put an example:</h3><h3>Challenge #1</h3><p>Build a TodoList component that should be able</p><ol><li>Fetch todos from server</li><li>Show loading state for user whiling fetching</li><li>If any error, display error</li><li>After fetching, render todos list</li></ol><p>It’s a good practice <a href="https://tailordev.fr/blog/2016/03/17/loading-dependencies-asynchronously-in-react-components/">resolve promises soon as possible</a>, so make sense use componentWillMount for that.. <strong>But ...</strong></p><h3>Riderman on Twitter</h3><p>Why the official #React site recommends use componentDidMount instead of componentWillMount for ajax request https://t.co/991t4F2wbp 🤔</p><p>And after make some research …</p><p><strong>Can be deprecate</strong></p><p>There are a big discussion <a href="https://github.com/facebook/react/issues/7671">on issue #7671</a> and <a href="https://github.com/yannickcr/eslint-plugin-react/issues/1147">eslint-react-plugin</a> about deprecate componentWillMount in flavor of constructor()</p><p><strong>Will not call the render again</strong></p><blockquote><em>As </em><em>componentWillMount doesn&#39;t trigger a re-render you won&#39;t have the behaviour you expected which is the component being rendered with the requested data.</em></blockquote><blockquote><em>— — </em><a href="https://hashnode.com/util/redirect?url=https://stackoverflow.com/a/43340442/491181"><em>stackoverflow.com/a/43340442/491181</em></a></blockquote><p><strong>It’s used on serve-side render</strong></p><blockquote><em>is rarely useful; especially if you care about server side rendering (adding event listeners causes errors and leaks, and lots of other stuff that can go wrong).</em></blockquote><blockquote><em>— — </em><a href="https://hashnode.com/util/redirect?url=https://stackoverflow.com/a/27139507/491181"><em>stackoverflow.com/a/27139507/491181</em></a></blockquote><p>..</p><blockquote><em>Invoked once, both on the client and server, immediately before the initial rendering occurs.</em></blockquote><blockquote><em>— - </em><a href="https://discuss.reactjs.org/t/constructor-vs-componentwillmount-vs-componentdidmount/4287/4"><em>https://discuss.reactjs.org/t/constructor-vs-componentwillmount-vs-componentdidmount/4287/4</em></a></blockquote><p><strong>You can’t cancel ajax</strong></p><blockquote><em>To not leak memory its a usually a good practice to cancel this request when the component is unmounted,</em></blockquote><blockquote><em>.. whatever reason the component did not mount. you still have your pending ajax request which can not be cancelled anywhere</em></blockquote><blockquote><em>— — </em><a href="https://hashnode.com/util/redirect?url=https://stackoverflow.com/a/39365138/491181"><em>stackoverflow.com/a/39365138/491181</em></a></blockquote><p>Thats the reason that <a href="https://facebook.github.io/react/docs/react-component.html#componentdidmount">React docs recommend</a> componentDidMount instead componentWillMount</p><blockquote><em>If you need to load data from a remote endpoint, this is a good place to instantiate the network request.</em></blockquote><h3>Using componentDidMount</h3><p>Following the react documentation, let’s put fetch request on componentDidMount.</p><p>To complete our task we need to notify the component that we are loading and after that, if there are any error, show the error.</p><pre>componentDidMount() {<br>    const { fetchTodos } = <strong>this</strong>.props.todoStore;<br>    <strong>this</strong>.setState({ isFetching: true }); // OPS<br>    const result = fetchTodos();<br>    <strong>when</strong>(() =&gt; result.state !== PENDING,<br>      () =&gt; {<br>        <strong>this</strong>.setState({ isFetching: false });<br>        result.case({<br>          rejected: error =&gt; <strong>this</strong>.setState({ error }),<br>        });<br>      },<br>    )    <br>  }</pre><p><strong>Perfect example..</strong></p><p>We make a request in fetchTodos that return an <a href="https://github.com/mobxjs/mobx-utils#frompromise">fromPomise </a>so we can use the result to set the loader this.setState({ isFetching: false });and error this.setState({ error }) if necessary.</p><p><strong>But, wait.. </strong>there are a problem here.. this.setState({ isFetching: true }); // OPS <a href="https://hashnode.com/post/why-is-it-a-bad-idea-to-call-setstate-immediately-after-componentdidmount-in-react-cim5vz8kn01flek53aqa22mby">will make the the <strong>component render agai</strong></a><strong>n</strong>.</p><blockquote><em>Doing </em><em>setState in </em><em>componentDidMount will cause a visible render flash.</em></blockquote><blockquote><em>--- </em><a href="https://hashnode.com/util/redirect?url=https://github.com/airbnb/javascript/issues/684#issuecomment-264094930"><em>github.com/airbnb/javascript/issues/684#iss..</em></a></blockquote><p>Thats the reason that <a href="https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-did-mount-set-state.md">has a ESLint rule</a> that prevent you to use setState on componentDidMount</p><p>They are a workaround for that.. simple put your initial state as isFetching :true in constructor</p><pre><strong>constructor</strong>(props) {<br>  <strong>super</strong>(props);<br>  <strong>this</strong>.state = {isFetching: true};<br>}</pre><p>This will make your TodoList start in loading mode, but this is ok.</p><p>The reason that this.setState({ isFetching: false }); inside the componentDidMount works because when is &quot;watching&quot; the property state of result, when the property change the callback will execute. So it&#39;s not executed in context of componentDidMount it&#39;s executed in context of when.</p><h3>Chalenge #2</h3><p>Build a TodoView component that display a single todo</p><ol><li>Should be able to complete/uncomplete the todo</li><li>Should display status while complete/uncomplete todo</li></ol><p>We can follow the same patter..</p><pre><strong>constructor</strong>(props) {<br>    <strong>super</strong>(props);<br>    <strong>this</strong>.setCompleted = <strong>this</strong>.setCompleted.bind(<strong>this</strong>);<br>    <strong>this</strong>.state = {isLoading: false};<br>}</pre><p>When user click on complete, we can &quot;watch&quot; for the property state and react on change</p><pre>setCompleted(isCompleted) {<br>    const { todo, todoStore } = <strong>this</strong>.props;<br>    <strong>this</strong>.setState({ isLoading: true });<br>    const result = todoStore.complete(todo.id, isCompleted);<br>    <strong>when</strong>(() =&gt; result.state !== PENDING,<br>    () =&gt; {<br>              <strong>this</strong>.setState({ isLoading: false });<br>        result.case({<br>            rejected: error =&gt; <strong>this</strong>.setState({ error }),<br>              fulfilled: (value) =&gt; {<br>              value.complete <br>                  ? $(<strong>this</strong>.checkInput).checkbox(&#39;check&#39;)<br>                    : $(<strong>this</strong>.checkInput).checkbox(&#39;uncheck&#39;)                      <br>                  }<br>          });<br>    });<br>}</pre><p>We are not inside of componentDidMount so it&#39;s ok to use this.setState({ isLoading: true }); on beginner.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjsfiddle.net%2FRidermansb%2Foa44y834%2Fembedded%2F&amp;url=https%3A%2F%2Fjsfiddle.net%2FRidermansb%2Foa44y834%2F%3Futm_source%3Dwebsite%26utm_medium%3Dembed%26utm_campaign%3Doa44y834&amp;image=https%3A%2F%2Fwww.gravatar.com%2Favatar%2F5728e1eaf86f796b7b626f322b1ad956%2F%3Fdefault%3D%26s%3D80&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2eb133116be97775104476235962692/href">https://medium.com/media/e2eb133116be97775104476235962692/href</a></iframe><blockquote><em>Like this? Please click ❤️ bellow so other people can find it.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86ab4054f43c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Update graph in D3]]></title>
            <link>https://medium.com/@ridermansb/update-graph-in-d3-30baaebcc8c3?source=rss-fe49a771c747------2</link>
            <guid isPermaLink="false">https://medium.com/p/30baaebcc8c3</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[d3]]></category>
            <category><![CDATA[svg]]></category>
            <category><![CDATA[d3js]]></category>
            <dc:creator><![CDATA[Ridermansb]]></dc:creator>
            <pubDate>Sun, 28 May 2017 03:53:34 GMT</pubDate>
            <atom:updated>2017-05-28T03:53:34.114Z</atom:updated>
            <content:encoded><![CDATA[<p>Some days ago I spend more than an hour to figure out how to update the graph when data change.</p><p>My goals is to update the position of element when data change.</p><p>For example, for each point A, B, C .. we have position X,Y.<br>If the position change I need to update the graph.</p><h3>Creating the graph</h3><p>To create this graph is pretty simple, we define some data..</p><pre>const data = [<br> {“id”: “A”, “x”: 2000, “y”: 2000 },<br> {“id”: “B”, “x”: 5000, “y”: 5000 },<br> {“id”: “C”, “x”: 10000, “y”: 10000 }<br>]</pre><pre>const letters = “DEFGHIJKLMNOPQRSTUVWXYZ”.split(‘’)<br></pre><p>Define the domain and scales..</p><pre>const el = document.getElementById(“matrix”)</pre><pre>const SIZE = {width: el.offsetWidth, height: el.offsetHeight};<br>const DOMAIN = {x: [20000, 0], y: [0, 20000]};<br>const SCALES = {<br> x: d3.scaleLinear().range([SIZE.width, 0]).domain(DOMAIN.x),<br> y: d3.scaleLinear().range([0, SIZE.height]).domain(DOMAIN.y)<br>}</pre><p>And then we are ready to populate our graph..</p><pre>const dot = svg<br> .selectAll(‘.dot’)<br> .data(data)<br> <br> dot.exit().remove()<br> <br> dot.select(‘circle’)<br> .attr(‘cx’, d =&gt; SCALES.x(d.x))<br> .attr(‘cy’, d =&gt; SCALES.y(d.y))</pre><pre>dot.select(‘text’)<br> .attr(‘x’, d =&gt; SCALES.x(d.x))<br> .attr(‘y’, d =&gt; SCALES.y(d.y)) <br> <br> let dotG = dot.enter()<br> .append(“g”)<br> .attr(‘class’, ‘dot’)<br> <br> dotG<br> .append(“circle”)<br> .attr(‘class’, ‘circle’)<br> .attr(‘fill’, ‘black’)<br> .attr(‘r’, ‘9’)<br> .attr(‘cx’, d =&gt; SCALES.x(d.x))<br> .attr(‘cy’, d =&gt; SCALES.y(d.y))<br> <br> dotG<br> .append(“text”)<br> .attr(‘class’, ‘letter’)<br> .attr(‘text-anchor’, ‘middle’)<br> .attr(‘fill’, ‘white’)<br> .attr(‘alignment-baseline’, ‘central’)<br> .text(d =&gt; d.id)<br> .attr(‘x’, d =&gt; SCALES.x(d.x))<br> .attr(‘y’, d =&gt; SCALES.y(d.y))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WaI4iNPDI_mhdslijaik1w.png" /></figure><p>But whats happens if we need to update the point position when data update?</p><h3>Updating graph when data change</h3><p>To archive that we need to understand two things in D3</p><ol><li>In DOM element we can bind and trigger events</li></ol><pre>$(el).bind(“updateD3”, function() { <br>   console.log(&#39;Updating …&#39;);<br>})<br>$(el).trigger(&quot;updateD3&quot;); // Updating ...</pre><p>This will help us because when we receive data update we simple call $(el.trigger(&#39;updateD3&#39;))</p><p>2. enter, remove will add/remove elements that aren’t in the data.</p><pre>const dot = svg<br> .selectAll(‘.dot’)<br> .data(data)<br> <br>dot.exit()<br> .remove() // Remove elements that are not in data<br>dot<br> .enter() // Return elements that are in data but not in svg</pre><p>We can use this both techniques to update our graph.</p><h3>Putting all togheder</h3><p>First lets move our graph definition to our event callbac</p><pre>$(el).bind(“updateD3”, function () {<br> <br> const dot = svg.selectAll(‘.dot’).data(data)<br> <br> dot.exit().remove() // Remove elements that are not in data<br> <br> dot.select(‘circle’)<br> .attr(‘cx’, d =&gt; SCALES.x(d.x))<br> .attr(‘cy’, d =&gt; SCALES.y(d.y))</pre><pre>dot.select(‘text’)<br> .attr(‘x’, d =&gt; SCALES.x(d.x))<br> .attr(‘y’, d =&gt; SCALES.y(d.y)) <br> <br> let dotG = dot.enter() // Return elements tha are in data but not in svg<br>  .append(“g”) // add this elements in svg<br> .attr(‘class’, ‘dot’)<br> <br> dotG<br> .append(“circle”)<br> .attr(‘class’, ‘circle’)<br> .attr(‘fill’, ‘black’)<br> .attr(‘r’, ‘9’)<br> .attr(‘cx’, d =&gt; SCALES.x(d.x))<br> .attr(‘cy’, d =&gt; SCALES.y(d.y))<br> <br> dotG<br> .append(“text”)<br> .attr(‘class’, ‘letter’)<br> .attr(‘text-anchor’, ‘middle’)<br> .attr(‘fill’, ‘white’)<br> .attr(‘alignment-baseline’, ‘central’)<br> .text(d =&gt; d.id)<br> .attr(‘x’, d =&gt; SCALES.x(d.x))<br> .attr(‘y’, d =&gt; SCALES.y(d.y))<br> <br>});</pre><p>Now, when data change all we need to do is trigger the event again</p><pre>$(el).trigger(“updateD3”);</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjsfiddle.net%2FRidermansb%2Fnumtbxft%2Fembedded%2F&amp;url=https%3A%2F%2Fjsfiddle.net%2FRidermansb%2Fnumtbxft%2F&amp;image=https%3A%2F%2Fwww.gravatar.com%2Favatar%2F5728e1eaf86f796b7b626f322b1ad956%2F%3Fdefault%3D%26s%3D80&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/518257098e77a1b4d92843e564958cb9/href">https://medium.com/media/518257098e77a1b4d92843e564958cb9/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30baaebcc8c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue.js 2.0 its here!]]></title>
            <link>https://medium.com/@ridermansb/vue-js-2-0-its-here-cf4be667e703?source=rss-fe49a771c747------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf4be667e703</guid>
            <dc:creator><![CDATA[Ridermansb]]></dc:creator>
            <pubDate>Sat, 08 Oct 2016 13:35:37 GMT</pubDate>
            <atom:updated>2016-10-08T13:35:37.325Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m curious, enthusiastic and student most of the time, like the rest of the time to write code, especially in javascript.</p><h4><a href="https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore?ct=t%28BrazilJS_Weekly_468_9_2013%29&amp;utm_campaign=Revue%20newsletter&amp;utm_medium=Newsletter&amp;utm_source=revue">you-dont-need/You-Dont-Need-Lodash-Underscore</a></h4><p><a href="https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore?ct=t(BrazilJS_Weekly_468_9_2013)">github.com</a> <br> Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.</p><figure><img alt="1*fsoztiuczczgz mjxg3 7g" src="https://cdn-images-1.medium.com/max/740/0*8jxB2It9n3oNDbUw." /></figure><p><a href="https://blog.codecasts.com.br/vue-js-e-servicos-4d4439320a2?gi=8e9af901b86b&amp;utm_campaign=Revue%20newsletter&amp;utm_medium=Newsletter&amp;utm_source=revue"><strong>Vue.js e Serviços</strong></a><strong> — </strong><a href="https://blog.codecasts.com.br/vue-js-e-servicos-4d4439320a2?gi=8e9af901b86b"><strong>blog.codecasts.com.br</strong></a></p><p>Criando e consumindo services com plugins</p><figure><img alt="6128107?1475751796" src="https://cdn-images-1.medium.com/max/740/0*PERapqy9srDcxsYs." /></figure><p><a href="https://github.com/vuejs/awesome-vue?utm_campaign=Revue%20newsletter&amp;utm_medium=Newsletter&amp;utm_source=revue#autocomplete"><strong>GitHub — vuejs/awesome-vue: A curated list of awesome things related to Vue.js</strong></a><strong> — </strong><a href="https://github.com/vuejs/awesome-vue#autocomplete"><strong>github.com</strong></a> <br> awesome-vue — A curated list of awesome things related to Vue.js</p><figure><img alt="Vue" src="https://cdn-images-1.medium.com/max/740/0*gWNG_-bvNjZ-NtfM." /></figure><p><a href="http://www.vuejs-brasil.com.br/como-funciona-a-reatividade-no-vue-js/?utm_campaign=Revue%20newsletter&amp;utm_medium=Newsletter&amp;utm_source=revue"><strong>Como funciona a reatividade no Vue.js — Comunidade Brasileira de Vue.js</strong></a><strong> — </strong><a href="http://www.vuejs-brasil.com.br/como-funciona-a-reatividade-no-vue-js/"><strong>www.vuejs-brasil.com.br</strong></a></p><p>Entenda um pouco do código do Vue.js</p><figure><img alt="1707116?1475607568" src="https://cdn-images-1.medium.com/max/740/0*umjnjA1LAfwoPzU6." /></figure><p><a href="https://github.com/BenjaminListwon/vue-vuex-demo?utm_campaign=Revue%20newsletter&amp;utm_medium=Newsletter&amp;utm_source=revue"><strong>GitHub — BenjaminListwon/vue-vuex-demo: An evolving demo of vuex functionality for Vue 2.0 / vuex 2.0</strong></a><strong> — </strong><a href="https://github.com/BenjaminListwon/vue-vuex-demo"><strong>github.com</strong></a> <br> vue-vuex-demo — An evolving demo of vuex functionality for Vue 2.0 / vuex 2.0</p><h3>Vue.js 2.0 Demos</h3><figure><img alt="6128107?1475607573" src="https://cdn-images-1.medium.com/max/740/0*4TmK7XMaDI7Ud_cV." /></figure><p><a href="https://github.com/vuejs/vue-hackernews-2.0?utm_campaign=Revue%20newsletter&amp;utm_medium=Newsletter&amp;utm_source=revue"><strong>GitHub — vuejs/vue-hackernews-2.0: HackerNews clone built with Vue 2.0, vue-router &amp; vuex, with server-side rendering</strong></a><strong> — </strong><a href="https://github.com/vuejs/vue-hackernews-2.0"><strong>github.com</strong></a> <br> vue-hackernews-2.0 — HackerNews clone built with Vue 2.0, vue-router &amp; vuex, with server-side rendering</p><figure><img alt="1707116?1475607524" src="https://cdn-images-1.medium.com/max/740/0*VLP4PFL1fMdlRq_s." /></figure><p><a href="https://github.com/BenjaminListwon/short-order-vue?utm_campaign=Revue%20newsletter&amp;utm_medium=Newsletter&amp;utm_source=revue"><strong>GitHub — BenjaminListwon/short-order-vue: A simple Vue 2.0 demo</strong></a><strong> — </strong><a href="https://github.com/BenjaminListwon/short-order-vue"><strong>github.com</strong></a> <br> short-order-vue — A simple Vue 2.0 demo</p><h3>Vue.js 2.0 Articles</h3><figure><img alt="Vue js 2   filtros em listas" src="https://cdn-images-1.medium.com/max/740/0*A6rr-D20cazXwPg6." /></figure><p><a href="http://www.vuejs-brasil.com.br/vue-js-2-filtros-em-listas/?ct=t%28BrazilJS_Weekly_468_9_2013%29&amp;utm_campaign=Revue%20newsletter&amp;utm_medium=Newsletter&amp;utm_source=revue"><strong>Vue.js 2 — Filtros em Listas — Comunidade Brasileira de Vue.js</strong></a><strong> — </strong><a href="http://www.vuejs-brasil.com.br/vue-js-2-filtros-em-listas/?ct=t(BrazilJS_Weekly_468_9_2013)"><strong>www.vuejs-brasil.com.br</strong></a> <br> Vue.js 2 removeu os filtros em listas. Veja como usar de forma simples, eficiente e performática os filtros em listas com computeds properties.</p><h3>Vue Tools</h3><figure><img alt="Open graph" src="https://cdn-images-1.medium.com/max/740/0*ydB2CYSVHXZjaq_3." /></figure><p><a href="https://www.npmjs.com/package/vue-gmaps?utm_campaign=Revue%20newsletter&amp;utm_medium=Newsletter&amp;utm_source=revue"><strong>vue-gmaps</strong></a><strong> — </strong><a href="https://www.npmjs.com/package/vue-gmaps"><strong>www.npmjs.com</strong></a></p><p>Search places (not just address) using Google Maps API</p><figure><img alt="6128107?1475607545" src="https://cdn-images-1.medium.com/max/740/0*ir_VVwXPxXFN2hZ8." /></figure><p><a href="https://github.com/vuejs/vue-touch?utm_campaign=Revue%20newsletter&amp;utm_medium=Newsletter&amp;utm_source=revue"><strong>Hammer.js wrapper for Vue.js</strong></a><strong> — </strong><a href="https://github.com/vuejs/vue-touch"><strong>github.com</strong></a> <br> vue-touch — Hammer.js wrapper for Vue.js</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf4be667e703" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>