<?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[The Coding Hype - Medium]]></title>
        <description><![CDATA[Articles about software development. Mainly focused on the following: Swift, Javascript, C, C++, Objective-C, Ruby, SQL, PostgreSQL, MondoDB. - Medium]]></description>
        <link>https://medium.com/thecodinghype?source=rss----9fceaf0f32f4---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>The Coding Hype - Medium</title>
            <link>https://medium.com/thecodinghype?source=rss----9fceaf0f32f4---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 02:50:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/thecodinghype" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Are you Hapi(.js)? (Part 2/2)]]></title>
            <link>https://medium.com/thecodinghype/are-you-hapi-js-part-2-2-ba38d1b9a947?source=rss----9fceaf0f32f4---4</link>
            <guid isPermaLink="false">https://medium.com/p/ba38d1b9a947</guid>
            <category><![CDATA[hapijs]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[cookies]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[stream]]></category>
            <dc:creator><![CDATA[László Harri Németh]]></dc:creator>
            <pubDate>Tue, 26 Mar 2019 09:01:01 GMT</pubDate>
            <atom:updated>2019-05-19T04:33:17.484Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jW38Va5V-K58hyc5" /><figcaption>Photo by <a href="https://unsplash.com/@sapegin?utm_source=medium&amp;utm_medium=referral">Artem Sapegin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article is the second part of a two-part series about <a href="https://hapijs.com/">Hapi.js</a>. The first part can be read <a href="https://medium.com/thecodinghype/are-you-hapi-js-part-1-2-4db58f4ae17e">here</a>. I suggest you to read the first part first.</p><blockquote><em>Keywords: Node.js, NPM, Javascript, Hapi.js, HTTP, Inert, Path, Fs, Rot13-transform, Joi, Hapi-auth-basic, Routing, Static files, Streams, Validation, Upload, Cookies, Authorization</em></blockquote><blockquote><strong><em>DISCLAIMER: THE VIEWS AND OPINIONS EXPRESSED IN THIS ARTICLE ARE THOSE OF THE AUTHOR AND DO NOT REFLECT THE OFFICIAL POLICY OR POSITION OF THE EMPLOYER OF THE AUTHOR. THE ARTICLE IS NOT ENDORSED BY, DIRECTLY AFFILIATED WITH, MAINTAINED, AUTHORIZED, OR SPONSORED BY ANY CORPORATION OR ORGANIZATION. THE INFORMATION CONTAINED ON THIS ARTICLE IS INTENDED SOLELY TO PROVIDE GENERAL GUIDANCE ON MATTERS OF INTEREST FOR THE PERSONAL USE OF THE READER, WHO ACCEPTS FULL RESPONSIBILITY FOR ITS USE. ALTHOUGH THE AUTHOR HAS MADE EVERY EFFORT TO ENSURE THAT THE INFORMATION IN THIS ARTICLE WAS CORRECT AT THE TIME OF THE WRITING, THE AUTHOR DOES NOT ASSUME AND HEREBY DISCLAIM ANY LIABILITY TO ANY PARTY FOR ANY LOSS, DAMAGE, OR DISRUPTION CAUSED BY ERRORS OR OMISSIONS, WHETHER SUCH ERRORS OR OMISSIONS RESULT FROM NEGLIGENCE, ACCIDENT, OR ANY OTHER CAUSE.</em></strong></blockquote><h3>Programming languages, technology</h3><p>This article involves the following programming languages and technology:</p><ul><li>Javascript</li><li>Node.js</li><li>hapi.js</li><li>HTTP</li></ul><p>The following node modules and Javascript libraries are used:</p><ul><li>hapi.js</li><li>inert</li><li>path (core module)</li><li>fs (core module)</li><li>rot13-transform</li><li>joi</li><li>boom</li><li>hapi-auth-basic</li></ul><h3>Table of Contents</h3><p>The article is divided into the following sections:</p><ul><li>Preparation, prerequisites</li><li>1.: Streams</li><li>2.: Validation</li><li>3.: Validation using JOI object</li><li>4.: Uploads</li><li>5.: Cookies</li><li>6.: Authentication</li><li>Closing words</li><li>License</li><li>References</li></ul><h3>1.: Streams</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0KB6Xj2dtRaP82Ng" /><figcaption>Photo by <a href="https://unsplash.com/@coryschadt?utm_source=medium&amp;utm_medium=referral">Cory Schadt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this exercise an additional module will be installed. This module is rot13-transform, and it implements the ROT13 transformation using streams.</p><blockquote>ROT13 (“rotate by 13 places”, sometimes hyphenated ROT-13) is a simple letter <a href="https://en.wikipedia.org/wiki/Substitution_cipher">substitution cipher</a> that replaces a letter with the 13th letter after it, in the alphabet. ROT13 is a special case of the <a href="https://en.wikipedia.org/wiki/Caesar_cipher">Caesar cipher</a> which was developed in ancient Rome. (Source: <a href="https://en.wikipedia.org/wiki/ROT13">Wikipedia</a>)</blockquote><p>Install this module:</p><pre>node install rot13-transform</pre><p>Further reading:</p><ul><li><a href="https://github.com/ajcrites/rot13-transform">ajcrites/rot13-transform</a></li><li><a href="https://www.npmjs.com/package/rot13-transform">rot13-transform</a></li><li><a href="https://en.wikipedia.org/wiki/ROT13">ROT13 - Wikipedia</a></li></ul><p>The fs core module of Node.js is used. In this example the content of a text file (<a href="https://gist.github.com/nlharri/261958c8b9b884c0037d7ee146dd8201#file-makemehapi-exercise-8-txt">makemehapi-exercise-8.txt</a>) is read up, and the ROT13 transformation is applied to the content of it (with the pipe() call, which I already mentioned in my earlier article about RxJS <a href="https://medium.com/thecodinghype/reactive-programming-in-javascript-using-rxjs-3b05e186c115">here</a>). The result is then returned to the client. The implementation looks like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b8003e411cb89debe7c22fdb3ca874b/href">https://medium.com/media/0b8003e411cb89debe7c22fdb3ca874b/href</a></iframe><h3>2.: Validation</h3><p>In this example Joi framework is used for validation. Joi is an object schema description language and validator for Javascript object.</p><pre>npm install joi</pre><p>In the following example path /chicken is defined and a parameter suffix named breed. The parameter is optional (which is indicated with the ? sign).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d94f447218ab44641b23e3fe4d36a698/href">https://medium.com/media/d94f447218ab44641b23e3fe4d36a698/href</a></iframe><p>If we navigate with the browser to the /chickens path, we get the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*TRxzBcmAQBPgegu9GORUGA.png" /></figure><p>Without the validation implementation (commenting out lines 28–34 and the , at the end of line 26) we get the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/143/1*Z6QEJTSyxFMaOQYaEGwL1w.png" /></figure><p>If we navigate to /chickens/Sussex, we get the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/153/1*YfmDviCiZ0VNjFBnKkYsAQ.png" /></figure><p>Further reading:</p><ul><li><a href="https://hapijs.com/api#path-parameters">17.8.1 API Reference</a></li><li><a href="https://hapijs.com/tutorials/validation">Validation</a></li><li><a href="https://github.com/hapijs/joi">GitHub - hapijs/joi: The most powerful data validation library for JS</a></li><li><a href="https://futurestud.io/tutorials/hapi-request-payload-validation-with-joi">hapi - Request Payload Validation With Joi</a></li></ul><h3>3.: Validation using JOI object</h3><p>By using a Joi object custom validation rules can be specified in<br>paths, request payloads, and responses.</p><p>In the example below complex conditions are defined for the parameters:</p><ul><li>isGuest is of type boolean, and a mandatory parameter</li><li>username is of type string and when isGuest is true, then username is mandatory (remember that isGuest is mandatory). (Otherwise username is not mandatory.)</li><li>accessToken is an alphanumeric string</li><li>password is an alphanumeric string</li></ul><p>When a post request is sent to the path /login, then these validations are executed on the payload.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/697b2d0d779627c73ada81d01dc47439/href">https://medium.com/media/697b2d0d779627c73ada81d01dc47439/href</a></iframe><p>More information:</p><p><a href="https://github.com/hapijs/joi/blob/master/API.md">hapijs/joi</a></p><h3>4.: Uploads</h3><p>This example shows how to upload file to the server using Hapi.js. I enhanced the original solution with a HTML page with which it is possible to test the implemented server.</p><p>Some important points of this code example:</p><ul><li>config has 2 properties: handler and payload</li><li>a Promise is returned in the handler</li></ul><pre>handler: (request, h) =&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>  &lt;...&gt;<br>  });<br>},<br>&lt;...&gt;</pre><ul><li>the file can be accessed with request.payload.<strong>uploadedFile</strong></li><li><strong>uploadedFile</strong> is the name in the &lt;input&gt; tag of the HTML:</li></ul><pre>&lt;input type=&quot;file&quot; name=&quot;<strong>uploadedFile</strong>&quot; size=&quot;40&quot;&gt;</pre><ul><li>the implementation reacts on 3 events: data, end and error</li></ul><pre>request.payload.uploadedFile.on(&#39;data&#39;, (data) =&gt; {</pre><pre>&lt;...&gt;</pre><pre>request.payload.uploadedFile.on(&#39;end&#39;, () =&gt; {</pre><pre>&lt;...&gt;</pre><pre>request.payload.uploadedFile.on(&#39;error&#39;, (err) =&gt; {</pre><ul><li>file data is collected to a variable</li></ul><pre>let body = &#39;&#39;;</pre><pre>&lt;...&gt;</pre><pre>body += data;</pre><ul><li>To accept the file as input and get the file as readable stream, the following is used:</li></ul><pre>payload: {<br>  output: &#39;stream&#39;,<br>  parse: true,<br>  allow: &#39;multipart/form-data&#39;<br>}</pre><ul><li>the example implementation does not save to file to the server, but prints some info about it, and the file contents as well</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*EAWMgHRa1eRR_5-hwH_vCA.png" /></figure><p>The implementation looks like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7768df9ce1a61c2688cd523a0f17545/href">https://medium.com/media/d7768df9ce1a61c2688cd523a0f17545/href</a></iframe><p>In my environment the app works the following way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*IzYgCLvkCl1YfQUpFXQk_w.gif" /></figure><h3>5.: Cookies</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mgS97X6J6SwyD4qZ" /><figcaption>Photo by <a href="https://unsplash.com/@charissek?utm_source=medium&amp;utm_medium=referral">Charisse Kenion</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This exercise is about handling cookies.</p><blockquote>An HTTP cookie (also called web cookie, Internet cookie, browser cookie, or simply cookie) is a small piece of data sent from a website and stored on the user’s computer by the user’s web browser while the user is browsing. Cookies were designed to be a reliable mechanism for websites to remember stateful information (such as items added in the shopping cart in an online store) or to record the user’s browsing activity (including clicking particular buttons, logging in, or recording which pages were visited in the past). They can also be used to remember arbitrary pieces of information that the user previously entered into form fields such as names, addresses, passwords, and credit card numbers. (source: <a href="https://en.wikipedia.org/wiki/HTTP_cookie">Wikipedia</a>)</blockquote><p>HTTP State Management Mechanism is defined in <a href="https://tools.ietf.org/html/rfc6265">RFC 6265</a>.</p><blockquote>“[…] the HTTP Cookie and Set-Cookie header fields […] can be used by HTTP servers to store state […] at HTTP user agents, letting the servers maintain a stateful session over the mostly stateless HTTP protocol. […] Using the Set-Cookie header field, an HTTP server can pass name/value pairs and associated metadata (called cookies) to a user agent. When the user agent makes subsequent requests to the server, the user agent uses the metadata and other information to determine whether to return the name/value pairs in the Cookie header. […] the server indicates a scope for each cookie when sending it to the user agent. The scope indicates the maximum amount of time in which the user agent should return the cookie, the servers to which the user agent should return the cookie […]. (source: <a href="https://tools.ietf.org/html/rfc6265">RFC 6265</a>)</blockquote><p>This implementation uses package boom which provides a set of utilities for returning HTTP errors.</p><pre>npm install boom</pre><p>In this example, the server responds to the following paths:</p><ul><li>set-cookie: sets a cookie with key session</li><li>check-cookie: checks the cookies if there is one with the key session. If yes, then returns { user: &#39;hapi&#39; }, otherwise returns an unauthorized error message</li></ul><p>The solution for this exercise works the following way:</p><ul><li>To use a cookie, it needs to be configured with server.state() call</li></ul><pre>server.state(&#39;session&#39;, {<br>  path: &#39;/&#39;,<br>  encoding: &#39;base64json&#39;,<br>  ttl: 10,<br>  domain: &#39;localhost&#39;,<br>  isSameSite: false,<br>  isSecure: false,<br>  isHttpOnly: false<br>});</pre><p>The above code tells the server the following:</p><p>— the path used is /</p><p>— the cookie should be base64json encoded</p><p>— the cookie expires in 10 milliseconds (for example, other option would be ttl: null which would set session lifetime, meaning the cookie will be deleted by the browser when closed)</p><p>— the domain scope of the cookie is localhost</p><p>More details about the isSecure attribute:</p><blockquote>The Secure attribute limits the scope of the cookie to “secure” channels (where “secure” is defined by the user agent). When a cookie has the Secure attribute, the user agent will include the cookie in an HTTP request only if the request is transmitted over a secure channel (typically HTTP over Transport Layer Security (TLS) [RFC2818]).</blockquote><blockquote>Although seemingly useful for protecting cookies from active network attackers, the Secure attribute protects only the cookie’s confidentiality. An active network attacker can overwrite Secure cookies from an insecure channel, disrupting their integrity (see Section 8.6 for more details). (<a href="https://tools.ietf.org/html/rfc6265#section-4.1.2.5">Source</a>)</blockquote><p>More details about the isHttpOnly attrbute:</p><blockquote>The HttpOnly attribute limits the scope of the cookie to HTTP requests. In particular, the attribute instructs the user agent to omit the cookie when providing access to cookies via “non-HTTP” APIs (such as a web browser API that exposes cookies to scripts).</blockquote><blockquote>Note that the HttpOnly attribute is independent of the Secure attribute: a cookie can have both the HttpOnly and the Secure attribute. (<a href="https://tools.ietf.org/html/rfc6265#section-4.1.2.6">Source</a>)</blockquote><ul><li>Navigation to the /set-cookie path will set a cookie with the key ‘session’ and the value { key: &#39;makemehapi&#39; }. This is achieved with the following handler</li></ul><pre>handler: (request, h) =&gt; {<br>  return h.response({<br>    message : &#39;success&#39;<br>  }).state(&#39;session&#39;, { key : &#39;makemehapi&#39; });<br>}</pre><ul><li>the cookie behaviour can be further configured at a route-level with the following</li></ul><pre>config<strong>:</strong> {<br>  state<strong>:</strong> {<br>    parse<strong>:</strong> true,      <em>// parse cookies and store in request.state</em><br>    failAction<strong>:</strong> &#39;log&#39; <em>// may also be &#39;error&#39; or &#39;log&#39;</em><br>  }<br>}</pre><ul><li>unauthorized error with the correct HTTP status can easily be returned with the help of an additional plugin called boom. This needs to be installed beforehand with npm install boom.</li><li>The check-cookie endpoint will have cookies received from the /set-cookie endpoint. If the session key is present in cookies then simply return { user: &#39;hapi&#39; }, otherwise return an unauthorized access error. This is done with the following route configuration:</li></ul><pre>server.route({<br>  method: &#39;GET&#39;,<br>  path: &#39;/check-cookie&#39;,<br>  handler: (request, h) =&gt; {<br>    var session = request.state.session;<br>    var result;</pre><pre>if (session) {<br>      result = { user : &#39;hapi&#39; };<br>    } else {<br>      result = Boom.unauthorized(&#39;Missing authentication&#39;);<br>    }<br>   <br>    return result;<br>  }<br>});</pre><p>To be able to run this in the browser, I modified some things compared to the official solution:</p><ul><li>I used process.env.IP and process.env.PORT as the IP address and port for the server</li><li>I used domain: process.env.IP in the server.state() call so that it will work in Cloud 9</li><li>I used ttl: null</li></ul><p>The source code of the solution is the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4c7d5d431dd563f20cac441ed03af54/href">https://medium.com/media/b4c7d5d431dd563f20cac441ed03af54/href</a></iframe><p>Further information:</p><ul><li><a href="https://github.com/hapijs/boom">hapijs/boom</a></li><li><a href="https://en.wikipedia.org/wiki/HTTP_cookie">HTTP cookie - Wikipedia</a></li><li><a href="https://hapijs.com/tutorials/cookies">Cookies</a></li><li><a href="https://tools.ietf.org/html/rfc6265">RFC 6265 - HTTP State Management Mechanism</a></li></ul><h3>6.: Authentication</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oKL-mjZ6LSqGSUnG" /><figcaption>Photo by <a href="https://unsplash.com/@kylejglenn?utm_source=medium&amp;utm_medium=referral">Kyle Glenn</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The Hapi plugin for handling basic authentication is called hapi-basic-auth:</p><pre>npm install hapi-auth-basic</pre><p>This is a basic authentication. With a help of a function we can authenticate a user and return if the authentication was successful or failed. (In this basic the password is a hard-coded plain text, but of course normally it should be stored encrypted.) In the example app, the username is hapi, the password is auth.</p><p>With server.auth.strategy(&#39;simple&#39;, &#39;basic&#39;, { validate }); we tell the server that it should use ‘simple’ auth. strategy, without setting it as default.</p><p>With server.auth.default(&#39;simple&#39;); we tell the server that this is the default authentication strategy, all routes added afterwards will follow this one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc506b13e8e59324811de3fea2ffdf64/href">https://medium.com/media/bc506b13e8e59324811de3fea2ffdf64/href</a></iframe><p>Further information:</p><ul><li><a href="https://hapijs.com/tutorials/auth">Authentication</a></li><li><a href="https://github.com/hapijs/hapi-auth-basic">hapijs/hapi-auth-basic</a></li><li><a href="https://futurestud.io/tutorials/hapi-basic-authentication-with-username-and-password">hapi - Basic Authentication With Username and Password</a></li></ul><h3>Closing words</h3><p>I hope you have learned something new today. Thank you for reading this article.</p><h3>License</h3><p>The code snippets used in this article are based on the original solutions for the workshop, therefore I reproduce here the license of makemehapi workshop.</p><pre>Copyright (c) 2012-2014, Walmart and other contributors.<br>All rights reserved.</pre><pre>Redistribution and use in source and binary forms, with or without<br>modification, are permitted provided that the following conditions are met:<br>    * Redistributions of source code must retain the above copyright<br>      notice, this list of conditions and the following disclaimer.<br>    * Redistributions in binary form must reproduce the above <br>      copyright notice, this list of conditions and the following <br>      disclaimer in the documentation and/or other materials <br>      provided with the distribution.<br>    * The names of any contributors may not be used to endorse or <br>      promote products derived from this software without specific <br>      prior written permission.</pre><pre>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &quot;AS IS&quot; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES<br>(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</pre><pre>*   *   *</pre><pre>The complete list of contributors can be found at: <a href="https://github.com/hapijs/makemehapi/graphs/contributors">https://github.com/hapijs/makemehapi/graphs/contributors</a></pre><p>Original version of the License:</p><p><a href="https://github.com/hapijs/makemehapi/blob/master/LICENSE">hapijs/makemehapi</a></p><h3>References</h3><ul><li><a href="https://hapijs.com/tutorials/">Getting Started</a></li><li><a href="https://hapijs.com/tutorials/plugins?lang=en_US">Plugins</a></li><li><a href="https://hapijs.com/tutorials/routing?lang=en_US">Routing</a></li><li><a href="https://hapijs.com/tutorials/serving-files?lang=en_US">Serving Static Content</a></li><li><a href="https://hapijs.com/tutorials/views">Views</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba38d1b9a947" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thecodinghype/are-you-hapi-js-part-2-2-ba38d1b9a947">Are you Hapi(.js)? (Part 2/2)</a> was originally published in <a href="https://medium.com/thecodinghype">The Coding Hype</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Are you Hapi(.js)?  (Part 1/2)]]></title>
            <link>https://medium.com/thecodinghype/are-you-hapi-js-part-1-2-4db58f4ae17e?source=rss----9fceaf0f32f4---4</link>
            <guid isPermaLink="false">https://medium.com/p/4db58f4ae17e</guid>
            <category><![CDATA[handlebars]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-server]]></category>
            <category><![CDATA[hapijs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[László Harri Németh]]></dc:creator>
            <pubDate>Tue, 05 Mar 2019 09:01:01 GMT</pubDate>
            <atom:updated>2019-03-05T09:01:00.882Z</atom:updated>
            <content:encoded><![CDATA[<h3>Are you Hapi(.js)? (Part 1/2)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*op1f2li_hjJvwywW" /><figcaption>Photo by <a href="https://unsplash.com/@rawpixel?utm_source=medium&amp;utm_medium=referral">rawpixel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://hapijs.com/">Hapi.js</a> is “A rich framework for building applications and services”. In the present article I will make some experiments with Hapi.js framework. I will show some simple scenarios using the framework. As a reference I use <a href="https://github.com/hapijs/makemehapi">Make Me Hapi</a>, which is a self-guided workshop to teach Hapi. I found it extremely useful for learning the basics of Hapi.js, and in this article I explain the official solutions for the exercises of the workshop. I modified the official solutions in some cases, therefore they will not always be run by the workshop.</p><p>This article is the first part of a two-part series.</p><blockquote><em>Keywords: Node.js, NPM, Javascript, Hapi.js, HTTP, Linux, Ubuntu, Template Engine, Inert, Path, Vision, Handlebars.js, H2o2, Routing, Static files, Directories, Templates, Proxy server</em></blockquote><blockquote><strong><em>DISCLAIMER: THE VIEWS AND OPINIONS EXPRESSED IN THIS ARTICLE ARE THOSE OF THE AUTHOR AND DO NOT REFLECT THE OFFICIAL POLICY OR POSITION OF THE EMPLOYER OF THE AUTHOR. THE ARTICLE IS NOT ENDORSED BY, DIRECTLY AFFILIATED WITH, MAINTAINED, AUTHORIZED, OR SPONSORED BY ANY CORPORATION OR ORGANIZATION. THE INFORMATION CONTAINED ON THIS ARTICLE IS INTENDED SOLELY TO PROVIDE GENERAL GUIDANCE ON MATTERS OF INTEREST FOR THE PERSONAL USE OF THE READER, WHO ACCEPTS FULL RESPONSIBILITY FOR ITS USE. ALTHOUGH THE AUTHOR HAS MADE EVERY EFFORT TO ENSURE THAT THE INFORMATION IN THIS ARTICLE WAS CORRECT AT THE TIME OF THE WRITING, THE AUTHOR DOES NOT ASSUME AND HEREBY DISCLAIM ANY LIABILITY TO ANY PARTY FOR ANY LOSS, DAMAGE, OR DISRUPTION CAUSED BY ERRORS OR OMISSIONS, WHETHER SUCH ERRORS OR OMISSIONS RESULT FROM NEGLIGENCE, ACCIDENT, OR ANY OTHER CAUSE.</em></strong></blockquote><h3>Programming languages, technology</h3><p>This article involves the following programming languages and technology:</p><ul><li>Javascript</li><li>Node.js</li><li>hapi.js</li><li>HTTP</li><li>Linux</li></ul><p>The following node modules and Javascript libraries are used:</p><ul><li>hapi.js</li><li>inert</li><li>path (core module)</li><li>vision</li><li>handlebars.js</li><li>h2o2</li></ul><h3>Table of Contents</h3><p>The article is divided into the following sections:</p><ul><li>Preparation, prerequisites</li><li>1.: Simple server</li><li>2.: Simple routing</li><li>3.: Serving static files</li><li>4.: Directories</li><li>5.: Templates</li><li>6.: Proxies</li><li>7.: Helper scripts</li><li>Closing words</li><li>License</li><li>References</li></ul><h3>Preparation, prerequisites</h3><p>The development environment I use is based on Ubuntu Linux 14.04.5 LTS (trusty), Nodejs v11.3.0, npm 6.4.1, nvm 0.33.11. I assume these are installed in your system. I’m using <a href="https://c9.io/">Cloud 9</a> environment.</p><p>To intall Hapi, you need to run</p><pre>npm install hapi</pre><p>Version of Hapi I use is 17.8.1.</p><p>In these examples I use process.env.IP and process.env.PORT instead of localhost and 8080. This is because of the Cloud 9 environment.</p><h3>1.: Simple server</h3><p>First this is an example of a simple web server.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9772511ccb9caab8652fd5960489de5f/href">https://medium.com/media/9772511ccb9caab8652fd5960489de5f/href</a></iframe><p>The app will show a “Hello hapi” text in the browser. It is important to observe how to start the server. It is put to an async function, and the server is started with await server.start().</p><p>Further reading:</p><ul><li><a href="https://javascript.info/async-await">Async/await</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await">await - JavaScript | MDN</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function">async function - JavaScript | MDN</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/async_function">async function expression - JavaScript | MDN</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction">AsyncFunction</a></li></ul><h3>2.: Simple routing</h3><p>In the previous example &#39;/&#39; was provided as path attribute. Paths can contain named parameters. In the example below, the parameter name is name and it is returned by accessing with request.params.name.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0dd4bfbcaf78f0768873dc3e3ff23ce/href">https://medium.com/media/e0dd4bfbcaf78f0768873dc3e3ff23ce/href</a></iframe><p>About encodeURIComponent(): according to the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent">documentation</a>, it <em>“encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two “surrogate” characters).”.</em></p><p>Further reading:</p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent">encodeURIComponent() - JavaScript | MDN</a></li><li><a href="https://stackoverflow.com/questions/4540753/should-i-use-encodeuri-or-encodeuricomponent-for-encoding-urls">Should I use encodeURI or encodeURIComponent for encoding URLs?</a></li></ul><h3>3.: Serving static files</h3><p>In order to send static files to the client an additional module is needed. This module is inert (current version is 5.1.2), which is installed with:</p><pre>npm install inert</pre><p>For this example need an additional module is used, which is the core modulepath. This example also contains an HTML file.</p><p>The server serves index.html to the client, when it is accessed with path /.</p><h4>Solution 1</h4><p>I needed to modify the coding because inter module must be registered for the server. Therefore server.route() calls are put in the initialization. In the end, I put the call to Hapi.Server() also in the initialization.</p><p>It is important to care about the proper file path on the server, for this we need to use Path.join(__dirname, &#39;index.html&#39;);.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17ef26b8cb99304900b5cc781e3d1203/href">https://medium.com/media/17ef26b8cb99304900b5cc781e3d1203/href</a></iframe><p>I left the code from the previous example here, so that paths like /name are also served.</p><h4>Solution 2</h4><p>As an alternative solution it is possible to configure a base path in your server and only pass relative path. The base path can be specified in routes. This way I can use index.html without specifying the absolute path.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/365bedb0db7eb167e508d9a47196adf9/href">https://medium.com/media/365bedb0db7eb167e508d9a47196adf9/href</a></iframe><h3>4.: Directories</h3><p>With the directory handler it is possible to access a file in a directory with a different path in the URL. It makes possible to specify one route to serve multiple files. The below route will respond to any request by looking for a matching filename in /foo/bar/baz directory. But it would respond with HTTP 403 if the directory itself is accessed without a file in the path. With the highlighted part of the code this can be fixed:</p><pre>server.route({<br>    path: &#39;/foo/bar/baz/{param*}&#39;, <br>    method: &#39;GET&#39;,<br>    handler: {<br>      directory: {<br>        path: Path.join(__dirname, &#39;public&#39;),<br><strong>        index: [&#39;index.html&#39;, &#39;default.html&#39;]<br></strong>      }<br>    }<br>  });</pre><p>When there is no index file available, inert can display the contents of the directory as a listing page. You can enable that by setting the listingproperty to true like so:</p><pre>server.route({<br>    path: &#39;/foo/bar/baz/{param*}&#39;, <br>    method: &#39;GET&#39;,<br>    handler: {<br>      directory: {<br>        path: Path.join(__dirname, &#39;public&#39;),<br><strong>        listing: true<br></strong>      }<br>    }<br>  });</pre><p>(The above two features are not included in the example below.)</p><p>In this example below we have a file.html in the /public directory of the server, and access this file with the /foo/bar/baz/file.html path. (We could access other files in the same /public path as well.)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f890ba2bf7b02906f8f86d77011a0485/href">https://medium.com/media/f890ba2bf7b02906f8f86d77011a0485/href</a></iframe><h3>5.: Templates</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*loZHkTPrVvlXYHqF" /><figcaption>Photo by <a href="https://unsplash.com/@ewan121?utm_source=medium&amp;utm_medium=referral">Ewan Robertson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This exercise shows the templating possibilities using Hapi.js. For this two additional modules are used:</p><ul><li>vision</li><li>handlebars.js</li></ul><ul><li><a href="https://handlebarsjs.com/">Handlebars</a></li><li><a href="https://github.com/hapijs/vision">hapijs/vision</a></li><li><a href="https://hapijs.com/tutorials/views">Views</a></li></ul><p>Let’s install these:</p><pre>node install vision handlebars</pre><p>For this example Inert module is not needed.</p><p>The vision plugin needs to be registered for the server:</p><pre>// Register Vision plugin<br>  await server.register(Vision);</pre><p>Also Handlebars module needs to be registered so that the templates will work. Handlebars is the engine responsible for rendering templates with an extension of .html.</p><pre>// Register Handlebars to handle templates<br>  server.views({<br>      engines: {<br>          html: Handlebars<br>      },<br>      path: Path.join(__dirname, &#39;templates&#39;)<br>  });</pre><p>In this example the server is called with /?name=World and it will process the templates in the /templates directory. As it can be seen, the index.html is a special HTML file which contains references which can be processed by Handlebars.js. With {{query.name}} the name parameter is referenced, and the content of it is put to the HTML page, which is sent back to the client.</p><p>The implementation is the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75f4e8d38fbc5a983f4884333f9929ad/href">https://medium.com/media/75f4e8d38fbc5a983f4884333f9929ad/href</a></iframe><h3>6.: Proxies</h3><p>In this exercise a proxy server is implemented. For this module h2o2 is needed.</p><pre>npm install -g h2o2</pre><p><a href="https://github.com/hapijs/h2o2">H2O2</a> is a proxy handler for Hapi.js. For this exercise there are 2 scripts. The first server is a proxy server running on port 8080 and this connects to the other server. When the proxy server is accessed with path /proxy it will connect to the another server. The other server is running on port 65535. This one will serve an HTML page. The two servers need to be run at the same time.</p><p>In the following code snippets the index.html file is served by the target server — under target server I mean the server which is accessed by the proxy server.</p><p>The script makemehapi-exercise-6-proxy.js contains the implementation of the proxy server. This will require h2o2, and set a proxy in the handler of the server route /proxy. This script needs to be run with node makemehapi-exercise-6-proxy.js.</p><p>The script makemehapi-exercise-6-target.js is the “target” server. This needs to be run with node makemehapi-exercise-6-target.js 65535.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b7689ee65d853ea3228db7cb96c6f52/href">https://medium.com/media/6b7689ee65d853ea3228db7cb96c6f52/href</a></iframe><blockquote>In computer networks, a proxy server is a server (a computer system or an application) that acts as an intermediary for requests from clients seeking resources from other servers. A client connects to the proxy server, requesting some service, such as a file, connection, web page, or other resource available from a different server and the proxy server evaluates the request as a way to simplify and control its complexity.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*hNodOSaQoZJpPYvzg4dN_w.png" /><figcaption>Proxy server (source: <a href="https://commons.wikimedia.org/wiki/File:Proxy_concept_en.svg">Wikipedia</a>)</figcaption></figure><blockquote>Communication between two computers (shown in grey) connected through a third computer (shown in red) acting as a proxy. Bob does not know to whom the information is going, which is why proxies can be used to protect privacy. (Source: <a href="https://en.wikipedia.org/wiki/Proxy_server">Wikipedia</a>)</blockquote><h3>7.: Helper scripts</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vzhKlQhCIwot1JTT" /><figcaption>Photo by <a href="https://unsplash.com/@reskp?utm_source=medium&amp;utm_medium=referral">Jametlene Reskp</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Further reading: <a href="https://hapijs.com/tutorials/views">Views, section “View helpers”</a>.</p><p>In Hapi.js it is possible to define view helpers. These are helper functions which can be used in the templates. In the following example the application prints out a fruit name, for which a parameter is received from the URL.</p><p>In the example below, helper.js should be in folder helpers. This helpers folder is registered in the server with the following:</p><pre>server.views({<br>  engines: { <br>    html: Handlebars<br>  },<br>  path: __dirname,<br><strong>  helpersPath: Path.join(__dirname, &#39;helpers&#39;)</strong><br>});</pre><p>The helper an implementation of a function which returns a value, which will be then used in the template, when the helper is referenced. For example, a simple helper.js file in the helpers folder looks like the following:</p><pre>module.exports = function (context) {<br>  value = &quot;&quot;;</pre><pre>  // ... implementation here ...</pre><pre>  // returning the value<br>  return value;<br>};</pre><p>Context is passed to the helper method.</p><p>In the template this is referenced with the name of the helper. For example, in a p tag:</p><pre>&lt;p&gt;{{helper}}&lt;/p&gt;</pre><p>In the helper implementation, with the context.data.root.query the query parameters in the URL can be accessed. For example in the URL</p><pre>https://localhost/?fruitName=3</pre><p>the value of fruitName can be accessed with:</p><pre>context.data.root.query.fruitName</pre><p>The example of helpers looks like the following. In this example fruits.js should be in the helpers folder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0af52301bb63d00c8c6a09ab3d0dcb7e/href">https://medium.com/media/0af52301bb63d00c8c6a09ab3d0dcb7e/href</a></iframe><h3>Closing words</h3><p>I hope you have learned something new today. Thank you for reading this article.</p><h3>License</h3><p>The code snippets used in this article are based on the original solutions for the workshop, therefore I reproduce here the license of makemehapi workshop. This is relevant for the code snippets posted in this article.</p><pre>Copyright (c) 2012-2014, Walmart and other contributors.<br>All rights reserved.</pre><pre>Redistribution and use in source and binary forms, with or without<br>modification, are permitted provided that the following conditions are met:<br>    * Redistributions of source code must retain the above copyright<br>      notice, this list of conditions and the following disclaimer.<br>    * Redistributions in binary form must reproduce the above <br>      copyright notice, this list of conditions and the following <br>      disclaimer in the documentation and/or other materials <br>      provided with the distribution.<br>    * The names of any contributors may not be used to endorse or <br>      promote products derived from this software without specific <br>      prior written permission.</pre><pre>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &quot;AS IS&quot; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES<br>(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</pre><pre>                               *   *   *</pre><pre>The complete list of contributors can be found at: <a href="https://github.com/hapijs/makemehapi/graphs/contributors">https://github.com/hapijs/makemehapi/graphs/contributors</a></pre><p>Original version of the License:</p><p><a href="https://github.com/hapijs/makemehapi/blob/master/LICENSE">hapijs/makemehapi</a></p><h3>References</h3><ul><li><a href="https://hapijs.com/tutorials/">Getting Started</a></li><li><a href="https://hapijs.com/tutorials/plugins?lang=en_US">Plugins</a></li><li><a href="https://hapijs.com/tutorials/routing?lang=en_US">Routing</a></li><li><a href="https://hapijs.com/tutorials/serving-files?lang=en_US">Serving Static Content</a></li><li><a href="https://hapijs.com/tutorials/views">Views</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4db58f4ae17e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thecodinghype/are-you-hapi-js-part-1-2-4db58f4ae17e">Are you Hapi(.js)?  (Part 1/2)</a> was originally published in <a href="https://medium.com/thecodinghype">The Coding Hype</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a simple note taking app for iOS in Swift]]></title>
            <link>https://medium.com/thecodinghype/creating-a-simple-note-taking-app-for-ios-in-swift-66dcbfe05a30?source=rss----9fceaf0f32f4---4</link>
            <guid isPermaLink="false">https://medium.com/p/66dcbfe05a30</guid>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[core-data-swift]]></category>
            <category><![CDATA[master-detail-application]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[László Harri Németh]]></dc:creator>
            <pubDate>Thu, 07 Feb 2019 09:42:07 GMT</pubDate>
            <atom:updated>2019-02-08T03:41:08.329Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*srnWp61pixDYCB7Iv1_LmA.jpeg" /></figure><p>This article describes details of a simple note taking app I created in Swift for iOS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*VDz_o-kcb_AVmUF1R4lF7A.png" /></figure><h3>The final product</h3><p>Here is a short summary about the final app I built. With the app it is possible to:</p><ul><li>Display and create notes</li><li>Edit notes</li><li>Delete notes</li></ul><p>The app will store for each note:</p><ul><li>The title of the note</li><li>The creation or last change date and time of the note</li><li>The text of the note</li></ul><p>The new note will only be created if the note title and note text are filled. The date and time stored for the note is updated with the current date and time, when the note is edited.</p><p>The app uses UIKit, and integrates with Core Data. As a starting point the Master-detail app template is used.</p><h4>Display and create notes</h4><p>The app start with a screen showing the list of notes.</p><p>Displaying a note shows a screen where the note title, creation / last edited date and time, and the note text are shown.</p><p>The creation of new notes is done from the note list screen using the + button. The OK button on the create screen is only active when both the description and the text of the note are filled. The back button leaves the create screen without creating the new note.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*JjQAWwJgmLRTZ-WrfIFZ1Q.gif" /></figure><h4>Edit notes</h4><p>From the display screen it is possible to navigate to an edit screen, which is the same as the create screen, except for that it will modify the edited note. The change can be saved with the OK button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*qgAYvhFggn-3dLHi6f8e8A.gif" /></figure><h4>Delete notes</h4><p>Deletion can be done by using the Edit button on the list screen. Alternatively the note can be dragged to the left, which will also delete the note.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*fSDSPa3SK_8amGWPitwwBA.gif" /></figure><blockquote><em>Keywords: Apple, iOS, Swift, UIKit, Core Data, note taking app</em></blockquote><blockquote><strong><em>DISCLAIMER: THE VIEWS AND OPINIONS EXPRESSED IN THIS ARTICLE ARE THOSE OF THE AUTHOR AND DO NOT REFLECT THE OFFICIAL POLICY OR POSITION OF THE EMPLOYER OF THE AUTHOR. THE ARTICLE IS NOT ENDORSED BY, DIRECTLY AFFILIATED WITH, MAINTAINED, AUTHORIZED, OR SPONSORED BY ANY CORPORATION OR ORGANIZATION. THE INFORMATION CONTAINED ON THIS ARTICLE IS INTENDED SOLELY TO PROVIDE GENERAL GUIDANCE ON MATTERS OF INTEREST FOR THE PERSONAL USE OF THE READER, WHO ACCEPTS FULL RESPONSIBILITY FOR ITS USE. ALTHOUGH THE AUTHOR HAS MADE EVERY EFFORT TO ENSURE THAT THE INFORMATION IN THIS ARTICLE WAS CORRECT AT THE TIME OF THE WRITING, THE AUTHOR DOES NOT ASSUME AND HEREBY DISCLAIM ANY LIABILITY TO ANY PARTY FOR ANY LOSS, DAMAGE, OR DISRUPTION CAUSED BY ERRORS OR OMISSIONS, WHETHER SUCH ERRORS OR OMISSIONS RESULT FROM NEGLIGENCE, ACCIDENT, OR ANY OTHER CAUSE.</em></strong></blockquote><h3>Table of Content</h3><p>The article is divided into the following sections:</p><ul><li>Why Swift and iOS?</li><li>Prerequisites</li><li>Preparation</li><li>XCode Project Setup</li><li>Integration with Core Data</li><li>Creating the UI</li><li>Handling the actions</li><li>Closing words</li><li>References</li></ul><h3>Why Swift and iOS?</h3><p>I’m not absolutely new to iOS development, although in the recent years I did not closely follow the innovation in this area. I met the iOS development first in 2011. I started to develop a mobile app prototype for the project I was working on those times. Back then Swift did not exist yet, Swift first appeared on June 2, 2014. I started learning Objective-C with the online courses of Stanford University, courses of Paul Hegarty were my favourites.</p><p>I really liked programming in Objective-C, and I wanted to learn more. However later on my interest turned to different technologies, and I didn’t continue with Objective-C. Some time ago I picked up iOS development again, and I started again with the Paul Hegarty’s Swift course on Youtube. It is a very good course to learn Swift and iOS development, with great example apps.</p><p>According to <a href="https://www.tiobe.com/tiobe-index/">TIOBE Index for January 2019</a>, (TIOBE index measures programming language popularity) Apple’s Swift language is on place 15.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Ve0W3kyePjN_xlsUdbKtQ.png" /></figure><p>Is it worth learning Swift nowadays? Using Swift means using Apple-based hardware, and Apple’s technology for development. No-one knows how successful the iOS platform is gong to be in the upcoming years. Even with these risks I think it definitely makes sense to start learning Swift. It will broaden your technological knowledge and understanding.</p><p>I am always excited to learn a new programming language. My opinion is that every programming language I learn offers me a new way of thinking. Writing high-quality and high-performance code has always been an art. For me getting in touch with a technology I’ve never worked with before is always time well-spent. This is especially true with a programming language with high interest.</p><blockquote>Apple open-sourced Swift and received a lot of help from the community to grow over the last few years. Ever since its inception, it has become tremendously popular and more mature than ever. Talking about the future of this amazing programming language, the developers are not going to abandon Swift because there is nothing like a native app with good performance and a good flow. (<a href="https://www.analyticsindiamag.com/heres-why-you-should-learn-apples-open-source-programming-language-swift/">Source: Here’s Why You Should Learn Apple’s Open Source Programming Language Swift — Analytics India Magazine</a>)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SMEKZJZskWunM4gN" /><figcaption>Photo by <a href="https://unsplash.com/@axellvak?utm_source=medium&amp;utm_medium=referral">Remy_Loz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Prerequisites</h3><p>For this tutorial you will need the following:</p><ul><li>A computer that runs Mac (If you don’t own an Apple computer, you can use <a href="https://macincloud.com/">MacinCloud</a>, for example.)</li><li>Operating system: macOS Mojave 10.14.2 (18C54)</li><li>XCode (I use version 10.1 (10B61))</li><li>Basic Swift knowledge</li></ul><h3>Preparation</h3><p>As a starting point I create a new XCode project, and start with the Master-Detail App template.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*Q5AcifAPTlx8RQL0MGuecw.png" /></figure><p>I fill the details of the new app the following way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*dfiqmbajblmnY_EXxEsfvw.png" /></figure><p>I don’t check “Use Core Data” because I will integrate with Core Data manually.</p><p>After creation of the new app, we can build and run it in the simulator. As you can see, this template app is a simple master-detail app, with which we can add new entries (time stamps) to a list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xKqLas_psuUwpSGg2XbKAA.png" /></figure><p>By selecting an element in the list we can see a details screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xQJs2uowKDhJ6gv7DiQa9A.png" /></figure><p>It is also possible to remove entries from the list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AKwclCTgp1uE9xho_VzdjQ.png" /></figure><p>This app will be the starting point for our new iOS note taking app.</p><h3>XCode Project Setup</h3><p>The XCode project we build will look have the following classes and groups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*ZgKW7E7tDRbC9hCLiSvGgg.png" /></figure><p>CoreDataModel group contains the model file for the Core Data integration.</p><p>Note group contains the implementation of Swift class handling the note object itself.</p><p>Storage group contains the implementation of the storage of the notes. This implementation is buit on the core data helper class, which is in the Helpers group.</p><p>Helpers group contains utility implementations for the date conversion and for the core data integration.</p><p>UI group contains the implementation of the ViewControllers, the UITableViewCell implementation assets (which is not used in this project), and the StoryBoards. (The LaunchScreen is not used in this project.)</p><p>The root folder contains the AppDelegate and the Info.plist which are created by XCode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KO22UpQoKQ7aAowUiRYzxA.jpeg" /></figure><h3>Integration with Core Data</h3><p>For storing the notes on the mobile device I use Core Data. In Core Data we need to define a data model, which we will use in the app to store the data.</p><h4>Creating a new Core Data model</h4><p>In order to integrate with Core Data, we need a new Core Data model. This can be created in XCode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*xsPBgIe_FIh9g-LDTwP6oQ.png" /><figcaption>Creating new Core Data model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*xGB9ASR6LRXFYvodlz2VYA.png" /><figcaption>Creating new Core Data model</figcaption></figure><p>Our Core Data model looks like the following. We have an entity, Note, and we have 4 attributes:</p><ul><li>noteId: the internal identifier of the note. Autogenerated by the application, not shown anywhere on the UI. Type of this attribute is UUID, Universal Unique Id.</li><li>noteText: text of the note</li><li>noteTimeStamp: an integer value which contains the time stamp of the creation / last change of the note</li><li>noteTitle: title of the note</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SYe6nRpFlBakKwiVx4ZqRg.png" /><figcaption>Core Data Model for the Really Simple Note Taking App</figcaption></figure><p>When creating a new XCode project we can check a checkbox which indicates that the app uses Core Data. If we check it, the app created by the template will contain the implementation to store the items in Core Data. I didn’t check this checkbox in the preparation steps, because I wanted to implement Core Data integration manually to learn it. Although I needed some code from the AppDelegate.swift, which is only generated when I use Core Data when creating the project.</p><p>This code looks like the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b6mdffmRVFmRpjk3PkAe3Q.png" /><figcaption>Core Data integration of AppDelegate.swift. Original file can be accessed <a href="https://github.com/nlharri/rsnt-really-simple-note-taking-ios/blob/master/rsnt-really-simple-note-taking-ios/AppDelegate.swift">here</a>.</figcaption></figure><p>This code is needed in AppDeleage.swift. Here the name <strong>ReallySimpleNotesData</strong> in NSPersistentContainer(name: &quot;<strong>ReallySimpleNotesData</strong>&quot;) refers to the name of the <strong>ReallySimpleNotesData</strong>.xcdatamodeld file we created.</p><h4>Storing time stamp in Core Data</h4><p>Storing time stamp in Core Data is an interesting topic. In Swift, the Date object has the timeIntervalSince1970 property, which is of type TimeInterval, and it contains the interval between the date value and 00:00:00 UTC on 1 January 1970. Type TimeInterval is an alias of type Double, and it means the number of seconds.</p><p>To get the seconds from this value, round it and convert it to Int64. The conversion to the other direction is also done this way. I do this by extending the Date type of Swift. This is done in ReallySimpleNoteDateHelper.swift.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e3PSbSf39hG6iBunCPhzJA.png" /><figcaption>Converting time stamp to seconds. Original implementation is <a href="https://github.com/nlharri/rsnt-really-simple-note-taking-ios/blob/master/rsnt-really-simple-note-taking-ios/Helpers/ReallySimpleNoteDateHelper.swift">here</a>.</figcaption></figure><p>The date helper implementation also contains a method to format the date properly. With this method I can show the date on the UI in Monday, Feb 4, 2019, 11:22:33 format. The implementation of the date helper class is the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ij9RsGIn6eduGTeeduI0og.png" /><figcaption>Date conversion helper. Original implementation <a href="https://github.com/nlharri/rsnt-really-simple-note-taking-ios/blob/master/rsnt-really-simple-note-taking-ios/Helpers/ReallySimpleNoteDateHelper.swift">here</a>.</figcaption></figure><h4>Note and Note Storage implementation</h4><p>The Note group contains the implementation for the Note. The class ReallySimpleNote is the container of the data of a note. It can be initialized by using UUID as well as without UUID. In case the instance is created without providing a UUID from outside, the UUID is generated using the <a href="https://developer.apple.com/documentation/foundation/uuid">UUID</a> which is part of the Foundation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8LOSm6411bfaksRVRBFcRA.png" /><figcaption>Implementation of ReallySimpleNote class. Original implementation is <a href="https://github.com/nlharri/rsnt-really-simple-note-taking-ios/blob/master/rsnt-really-simple-note-taking-ios/Note/ReallySimpleNote.swift">here</a>.</figcaption></figure><p>The instances of ReallySimpleNote are used throughout the app to transfer note data. The notes are stored in Core Data. For handling the integration with Core Data, we have two classes:</p><ul><li><a href="https://github.com/nlharri/rsnt-really-simple-note-taking-ios/blob/master/rsnt-really-simple-note-taking-ios/Storage/ReallySimpleNoteStorage.swift">ReallySimpleNoteStorage</a>: handles the operation of creating, reading, updating and deleting a note. Holds an instance to NSManagedObjectContext, which is necessary for the integration with Core Data. The operations are forwarded to the Core Data helper class, which communicates with Core Data.</li><li><a href="https://github.com/nlharri/rsnt-really-simple-note-taking-ios/blob/master/rsnt-really-simple-note-taking-ios/Helpers/ReallySimpleNoteCoreDataHelper.swift">ReallySimpleNoteCoreDataHelper</a>: manages the creation, reading, update and deletion of notes towards Core Data.</li></ul><p>NSManagedContext is provided to ReallySimpleNoteStorage by the MasterViewController, in the viewDidLoad() method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9PKpXzMxSoXybK1o5mKtlg.png" /><figcaption>Setting managed context in the note storage, by the MasterViewController.</figcaption></figure><p>The note storage class, ReallySimpleNoteStorage maintains a dictionary to map note indices to noteId’s. The UI identifies the notes by their index, but in Core Data their identifier is a UUID. The mapping between these two identifiers is stored and maintained in ReallySimpleNoteStorage. Calls to ReallySimpleNoteStorage are forwared to ReallySimpleNoteCoreDataHelper. For example, reading a note by index is implemented the following way in ReallySimpleNoteStorage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UaFe7QbI7ImMDLAyjf1cZw.png" /><figcaption>Creating a new note in note storage. Original implementation <a href="https://github.com/nlharri/rsnt-really-simple-note-taking-ios/blob/master/rsnt-really-simple-note-taking-ios/Storage/ReallySimpleNoteStorage.swift">here</a>.</figcaption></figure><h4>Core Data helper implementation</h4><p>ReallySimpleNoteCoreDataHelper class has static methods and handles the reading, modification and saving of notes to Core Data. It needs an instance of NSManagedObjectContext object, which is provided to it by using a parameter in each and every method.</p><p>For example, the creation of a new note in Core Data can be done by calling the createNoteInCoreData() method. This method is called from ReallySimpleNoteStorage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mTmzUufhocwzRZShS6Zt-A.png" /><figcaption>Creating a new note with Core Data. Original implementation <a href="https://github.com/nlharri/rsnt-really-simple-note-taking-ios/blob/master/rsnt-really-simple-note-taking-ios/Helpers/ReallySimpleNoteCoreDataHelper.swift">here</a>.</figcaption></figure><h3>Creating the UI</h3><p>The template app we used as a starting point creates the storyboard for the app. I extended this storyboard with one more ViewController Scene. For the Master ViewController, Detail ViewController and Create/Change ViewController I have separate implementation classes.</p><p>In these ViewController classes I call helper classes to store and retrieve data from the Core Data storage. I also call the Date Helper class shown earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*1nBeXFQYpDP49MqFePbEkA.png" /><figcaption>Storyboard of the note taking app. The ViewControllers indicated are created by the template. The one on the right is the create / change ViewController created by me.</figcaption></figure><p>The ViewControllers are connected by Segue’s to navigate between them. Most of these Segues are created by the template app by default, but there are 3 Segue’s, which I needed to add:</p><ul><li>navigation to the create screen by the + button. The template just created a new entry in the list without navigation to another screen.</li><li>navigation from the display screen to the change screen</li><li>navigation from the create / change screen back to the list of notes screen (this segue is called backToMasterView)</li></ul><p>For these Segue’s I needed to use “Show (e.g. Push)” kind.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*8vEDlD8tM59bXPqVVejtSQ.png" /><figcaption>Navigation to create screen from the list of notes screen.</figcaption></figure><p>The navigation from the Create / Change screen to the main screen is implemented in the ViewController ReallySimpleNoteCreateChangeViewController by calling performSegue().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_wDoRBQRnfC5QAqbcHfSdg.png" /><figcaption>Creating a new note and changing an existing one in the ViewController. Original implementation <a href="https://github.com/nlharri/rsnt-really-simple-note-taking-ios/blob/master/rsnt-really-simple-note-taking-ios/UI/ReallySimpleNoteCreateChangeViewController.swift">here</a>.</figcaption></figure><h3>Handling the actions</h3><p>UI elements are connected to class attributes with IBOutlets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q9gpw9s96CrxkSJPAK-v5Q.png" /></figure><h4>When the view was loaded</h4><p>When the view was loaded, we need to set some defaults for the UI elements. This is implemented in the viewDidLoad() method. What is done here is the following:</p><ul><li>set the ViewController as the delegate for the note text view</li><li>prefill contents of the fields when we are editing a note</li><li>set content of time stamp label</li><li>set border width, radius and color of the note text view</li><li>change text of back button in navigation bar</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wpDQNAfHPFkBKjF8MVMLDA.png" /><figcaption>viewDidLoad() method of the create / change ViewController. Original implementation <a href="https://github.com/nlharri/rsnt-really-simple-note-taking-ios/blob/master/rsnt-really-simple-note-taking-ios/UI/ReallySimpleNoteCreateChangeViewController.swift">here</a>.</figcaption></figure><h4>Enabling / disabling the OK button</h4><p>When a new note is created, the OK button should be enabled only in case there are some text entered in the title and in the text field. For this, the ReallySimpleNoteCreateChangeViewController class implements the handler for the Editing Changed and Value Changed events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*l0fxSNidSRlC6hhPaIRxZA.png" /></figure><p>The class also implements the UITextViewDelegate protocol, so that we can react to the change of the note text. In change mode (when we edit an already existing note), the OK button is enabled by default.</p><p>For example, the handling of enabling / disabling of the OK button when the note title changes, is implemented in the following way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zcqfiMWnw_bfbOxEDMpzPQ.png" /><figcaption>Enabling / disabling OK button. Original implementation <a href="https://github.com/nlharri/rsnt-really-simple-note-taking-ios/blob/master/rsnt-really-simple-note-taking-ios/UI/ReallySimpleNoteCreateChangeViewController.swift">here</a>.</figcaption></figure><p>The ReallySimpleNoteCreateChangeViewController is registered as a delegate for the note text view field. This way the app can react on changes to the content of the text view. For this the textViewDidChange() method was implemented.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RmWglteAYggv_0R46fnpRw.png" /><figcaption>React to the change in the note text. Original implementation <a href="https://github.com/nlharri/rsnt-really-simple-note-taking-ios/blob/master/rsnt-really-simple-note-taking-ios/UI/ReallySimpleNoteCreateChangeViewController.swift">here</a>.</figcaption></figure><h3>What’s missing?</h3><p>Throughout this article and app I didn’t implement proper error handling. The code still contains TODO comment referring to appropriate error handling. This topic I will cover later in a separate article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qlQtrt2PnnQryvSD-KK4TA.png" /></figure><h3>Closing words</h3><p>Thank you for reading this article. I hope you have learned somethinf new today. The app can be accessed on my Github profile:</p><p><a href="https://github.com/nlharri/rsnt-really-simple-note-taking-ios">nlharri/rsnt-really-simple-note-taking-ios</a></p><h3>References</h3><ul><li><a href="https://freakycoder.com/ios-notes-22-how-to-get-current-time-as-timestamp-fa8a0d422879">iOS Notes 22 : How to get current time as Timestamp?</a></li><li><a href="https://stackoverflow.com/questions/40134323/date-to-milliseconds-and-back-to-date-in-swift/40135172">Date to milliseconds and back to date in Swift</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66dcbfe05a30" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thecodinghype/creating-a-simple-note-taking-app-for-ios-in-swift-66dcbfe05a30">Creating a simple note taking app for iOS in Swift</a> was originally published in <a href="https://medium.com/thecodinghype">The Coding Hype</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple read REST API with Express.js and Node.js]]></title>
            <link>https://medium.com/thecodinghype/simple-read-rest-api-with-express-js-and-node-js-675a96ea6fe6?source=rss----9fceaf0f32f4---4</link>
            <guid isPermaLink="false">https://medium.com/p/675a96ea6fe6</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[odata]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[László Harri Németh]]></dc:creator>
            <pubDate>Tue, 22 Jan 2019 09:01:01 GMT</pubDate>
            <atom:updated>2019-01-22T09:01:00.927Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FQ5tHltry7B5HjGJ" /><figcaption>“MacBook Pro beside mug on table” by <a href="https://unsplash.com/@tomstanislavsky?utm_source=medium&amp;utm_medium=referral">Tomáš Stanislavský</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This short article shows how to create a simple read REST API with Node.js and Express.js.</p><blockquote><em>Keywords: Node.js, Javascript, REST API, Express.js, Routing</em></blockquote><blockquote><strong><em>DISCLAIMER: THE VIEWS AND OPINIONS EXPRESSED IN THIS ARTICLE ARE THOSE OF THE AUTHOR AND DO NOT REFLECT THE OFFICIAL POLICY OR POSITION OF THE EMPLOYER OF THE AUTHOR. THE ARTICLE IS NOT ENDORSED BY, DIRECTLY AFFILIATED WITH, MAINTAINED, AUTHORIZED, OR SPONSORED BY ANY CORPORATION OR ORGANIZATION. THE INFORMATION CONTAINED ON THIS ARTICLE IS INTENDED SOLELY TO PROVIDE GENERAL GUIDANCE ON MATTERS OF INTEREST FOR THE PERSONAL USE OF THE READER, WHO ACCEPTS FULL RESPONSIBILITY FOR ITS USE. ALTHOUGH THE AUTHOR HAS MADE EVERY EFFORT TO ENSURE THAT THE INFORMATION IN THIS ARTICLE WAS CORRECT AT THE TIME OF THE WRITING, THE AUTHOR DOES NOT ASSUME AND HEREBY DISCLAIM ANY LIABILITY TO ANY PARTY FOR ANY LOSS, DAMAGE, OR DISRUPTION CAUSED BY ERRORS OR OMISSIONS, WHETHER SUCH ERRORS OR OMISSIONS RESULT FROM NEGLIGENCE, ACCIDENT, OR ANY OTHER CAUSE.</em></strong></blockquote><h3>Required knowledge</h3><p>In order to understand this article you will need at least basic knowledge of</p><ul><li>Javascript</li><li>Linux</li><li>Node.js</li><li>NPM</li><li>Express.js</li></ul><h3>Initialization</h3><p>We will use the folder name rest-api-express-node. The following commands will initialize this folder for us:</p><pre>mkdir rest-api-express-node<br>cd rest-api-express-node<br>npm init -y</pre><h3>Install express.js</h3><pre>npm install --save express</pre><p>The implementation of a simple web server looks like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d3d9675c9c1dc858ebb3b767bd41549/href">https://medium.com/media/5d3d9675c9c1dc858ebb3b767bd41549/href</a></iframe><h3>Routing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t3IEteZcjKbXC_HT" /><figcaption>“aerial photo of gray concrete top roads” by <a href="https://unsplash.com/@_m_v_?utm_source=medium&amp;utm_medium=referral">_M_V_</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We need to specify routes for the web server. For this we will use another javascript file, routes.js.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2221e3ffed1dec9fcb05fbf4737169c/href">https://medium.com/media/b2221e3ffed1dec9fcb05fbf4737169c/href</a></iframe><p>This implementation will return the string REST API call of &#39;/&#39; every time the server root / is accessed. We will need to include this file in our index.js. The updated index.js looks like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff3bf0c4dd58ea6dcdc91d30290cc2cd/href">https://medium.com/media/ff3bf0c4dd58ea6dcdc91d30290cc2cd/href</a></iframe><h3>Route parameters</h3><p>For this tutorial we will use route parameter feature of express.js. For more information see the <a href="http://expressjs.com/en/guide/routing.html">express.js documentation</a>. We will implement the query of a todo entry by using the following URL: /todos/:todoid. Route parameters are named URL segments that are used to capture the values specified at their position in the URL. In our example todoid is a route parameter, When this kind of URL is accessed, we will return a dummy todo entry which we will generate on the fly. We need to modify routes.js:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a231b0e6f8877943c2f7f93a790ca49c/href">https://medium.com/media/a231b0e6f8877943c2f7f93a790ca49c/href</a></iframe><p>We can run the app:</p><pre>node index.js</pre><p>Enter http://localhost:3000/todos/123 to the URL in a browser.</p><p>This is just a very simple tutorial and test app to show the basics of using express routes and to return data in JSON format.</p><h3>What are Future Plans for this Project?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q_IUun0vf9tVusQM" /><figcaption>“photo of white painted building” by <a href="https://unsplash.com/@gdtography?utm_source=medium&amp;utm_medium=referral">gdtography</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><ul><li>Enhance with further operations: query, create, delete, update</li><li>Enhance with database access</li></ul><p>The final project can be accessed on my Github page:</p><p><a href="https://github.com/nlharri/simple-read-rest-api-express-node">nlharri/simple-read-rest-api-express-node</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=675a96ea6fe6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thecodinghype/simple-read-rest-api-with-express-js-and-node-js-675a96ea6fe6">Simple read REST API with Express.js and Node.js</a> was originally published in <a href="https://medium.com/thecodinghype">The Coding Hype</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reading from MongoDB database using Express.js and Node.js]]></title>
            <link>https://medium.com/thecodinghype/https-medium-com-thecodinghype-reading-from-mongodb-database-using-express-js-and-node-js-250ef8b9282a?source=rss----9fceaf0f32f4---4</link>
            <guid isPermaLink="false">https://medium.com/p/250ef8b9282a</guid>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[László Harri Németh]]></dc:creator>
            <pubDate>Wed, 02 Jan 2019 09:01:01 GMT</pubDate>
            <atom:updated>2019-01-02T09:01:01.575Z</atom:updated>
            <content:encoded><![CDATA[<h3>Reading from MongoDB database in Javascript with MongoClient</h3><p>This is a short tutorial and an example app which reads data from a MongoDB database. The app is using MongoDB, Express.js and Node.js. I’m using Apple macOS High Sierra 10.13.4 (17E199), Node.js v9.10.1, npm 5.6.0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*neb6jcCOMtzixfyG" /><figcaption>“MacBook Pro showing vegetable dish” by <a href="https://unsplash.com/@igormiske?utm_source=medium&amp;utm_medium=referral">Igor Miske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><em>Keywords: Node.js, NPM, Javascript, MongoDB, MongoClient, Express.js, macOS</em></blockquote><blockquote><strong><em>DISCLAIMER: THE VIEWS AND OPINIONS EXPRESSED IN THIS ARTICLE ARE THOSE OF THE AUTHOR AND DO NOT REFLECT THE OFFICIAL POLICY OR POSITION OF THE EMPLOYER OF THE AUTHOR. THE ARTICLE IS NOT ENDORSED BY, DIRECTLY AFFILIATED WITH, MAINTAINED, AUTHORIZED, OR SPONSORED BY ANY CORPORATION OR ORGANIZATION. THE INFORMATION CONTAINED ON THIS ARTICLE IS INTENDED SOLELY TO PROVIDE GENERAL GUIDANCE ON MATTERS OF INTEREST FOR THE PERSONAL USE OF THE READER, WHO ACCEPTS FULL RESPONSIBILITY FOR ITS USE. ALTHOUGH THE AUTHOR HAS MADE EVERY EFFORT TO ENSURE THAT THE INFORMATION IN THIS ARTICLE WAS CORRECT AT THE TIME OF THE WRITING, THE AUTHOR DOES NOT ASSUME AND HEREBY DISCLAIM ANY LIABILITY TO ANY PARTY FOR ANY LOSS, DAMAGE, OR DISRUPTION CAUSED BY ERRORS OR OMISSIONS, WHETHER SUCH ERRORS OR OMISSIONS RESULT FROM NEGLIGENCE, ACCIDENT, OR ANY OTHER CAUSE.</em></strong></blockquote><h3>Required knowledge</h3><p>In this article I will use the following technologies:</p><ul><li>Linux</li><li>Javascript</li><li>Node.js</li><li>Express.js</li><li>MongoDB</li><li>MongoClient</li></ul><h3>Table of Contents</h3><p>This article has the following sections:</p><ul><li>MongoDB installation</li><li>Data preparation</li><li>Express app creation</li><li>Express server implementation: without db read</li><li>Express server implementation: implementing db read using MongoDB Node.js driver</li><li>Closing words</li></ul><h3>MongoDB installation</h3><blockquote>MongoDB is a free and open-source cross-platform document-oriented NoSQL database program, which uses JSON-like documents with schemas. Express.js is a minimalist web application framework or Node.js. Node.js is an open-source, cross-platform JavaScript run-time environment that executes JavaScript code server-side. (Source: <a href="https://en.wikipedia.org/wiki/MongoDB">Wikipedia</a>)</blockquote><p>First we need to install MongoDB. In this article I will install it by downloading community server from mongodb.com. Let’s extract the tgz file. I will use ~/mongodb to store the mongodb runtime.</p><pre>cd ~<br>tar -zxvf mongodb-osx-ssl-x86_64-3.6.3.tgz<br>mv mongodb-osx-ssl-x86_64-3.6.3 mongodb</pre><p>MongoDB (mongod) defaults the database location to /data/db/.</p><p>Let’s create this directory, and change its owner (id -un gets the username):</p><pre>sudo mkdir -p /data/db<br>sudo chown -R `id -un` /data/db</pre><p>Now we can start the MongoDB server (mongod):</p><pre>cd ~<br>./mongodb/bin/mongod</pre><h3>Data preparation</h3><p>In this step we prepare the test data in our MongoDB database, so that we can use it in our app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tmPOt3FXDV-eB9NC" /><figcaption>“photo of 5-story library building” by <a href="https://unsplash.com/@tofi?utm_source=medium&amp;utm_medium=referral">Tobias Fischer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In a different shell window we need to start the MongoDB shell (mongo).</p><pre>./mongodb/bin/mongo</pre><p>In the MongoDB shell we can issue commands to the mongodb server to manipulate data in the database.</p><p>MongoDB stores data records in collections and the collections in databases. In this step we will create a new database called tododb. For this we will use the use statement.</p><pre>use tododb</pre><p>(The shell will return switched to db tododb.)</p><p>We will create a new collection todolist in this tododb database, and a new document in this todolist collection. The following command will create the collection as well as the new document.</p><pre>db.todolist.insertOne({description: &#39;Register for the marathon&#39;, details: &#39;it must be done until 4.7.2018&#39;})</pre><p>The shell returns something like the following:</p><pre>{<br>	&quot;acknowledged&quot; : true,<br>	&quot;insertedId&quot; : ObjectId(&quot;5ac8fbc723f00907d3d1be99&quot;)<br>}</pre><p>This means the document was created successfully. You can query this by the following command:</p><pre>db.todolist.find()</pre><p>Result:</p><pre>{ &quot;_id&quot; : ObjectId(&quot;5ac8fbc723f00907d3d1be99&quot;), &quot;description&quot; : &quot;Register for the marathon&quot;, &quot;details&quot; : &quot;it must be done until 4.7.2018&quot; }</pre><p>Or in a formatted way:</p><pre>db.todolist.find().pretty()</pre><p>Result:</p><pre>{<br>	&quot;_id&quot; : ObjectId(&quot;5ac8fbc723f00907d3d1be99&quot;),<br>	&quot;description&quot; : &quot;Register for the marathon&quot;,<br>	&quot;details&quot; : &quot;it must be done until 4.7.2018&quot;<br>}</pre><p>Let’s add another entry to the todolist:</p><pre>db.todolist.insertOne({description: &#39;Get money from ATM&#39;, details: &#39;100 USD&#39;})</pre><h3>Express app creation</h3><p>In this step we will create an express app. For this we need a new directory. We initialize the content (actually the package.jsonfile) with npm.</p><pre>npm init -y</pre><p>We need to install Express by issuing the following command. --save will save the dependency to package.json. We will also install mongodb which is the official MongoDB driver for Node.js.</p><pre>npm install --save express mongodb</pre><h3>Express server implementation: without db read</h3><p>Create index.js:</p><pre>touch index.js</pre><p>The implementation of the server looks like the following. This needs to be put to index.js</p><pre>var express = require(&#39;express&#39;);<br>var app = express();</pre><pre>app.get(&#39;/&#39;, (req, res) =&gt; {res.send(&#39;Hello World!&#39;)})<br>app.listen(3000, () =&gt; console.log(&#39;Example app listening on port 3000!&#39;))</pre><p>The app can be run by issuing the following command:</p><pre>node index.js</pre><p>And then in the web browser enter localhost:3000 to the URL.</p><h3>Express server implementation: implementing db read using MongoDB Node.js driver</h3><p>To read the data from the database the MongoDB Node.js driver MongoClient is used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6g07KUtdhUj5KspX" /><figcaption>“closeup photo of eyeglasses” by <a href="https://unsplash.com/@ikukevk?utm_source=medium&amp;utm_medium=referral">Kevin Ku</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>For this we need to enhance index.js. The final code looks like the following. Please see the comments.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/978ec0869b09e7b58c735e31b5c6ea47/href">https://medium.com/media/978ec0869b09e7b58c735e31b5c6ea47/href</a></iframe><p>The app can be started using</p><pre>node index.js</pre><h3>Closing words</h3><p>Thank you for reading this article. You can find the final implementation in my Github page:</p><p><a href="https://github.com/nlharri/read-db-data-mongodb-express-node">nlharri/read-db-data-mongodb-express-node</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=250ef8b9282a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thecodinghype/https-medium-com-thecodinghype-reading-from-mongodb-database-using-express-js-and-node-js-250ef8b9282a">Reading from MongoDB database using Express.js and Node.js</a> was originally published in <a href="https://medium.com/thecodinghype">The Coding Hype</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Experimenting with Ruby, Sinatra and PostgreSQL: a Message Board App]]></title>
            <link>https://medium.com/thecodinghype/experimenting-with-ruby-sinatra-and-postgresql-a-message-board-app-4ff2610c85e4?source=rss----9fceaf0f32f4---4</link>
            <guid isPermaLink="false">https://medium.com/p/4ff2610c85e4</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[css3]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[sinatra]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[László Harri Németh]]></dc:creator>
            <pubDate>Tue, 18 Dec 2018 09:01:01 GMT</pubDate>
            <atom:updated>2018-12-18T09:01:00.940Z</atom:updated>
            <content:encoded><![CDATA[<p>Although it’s 2018, and the first version of Ruby was released in 1995, 23 years ago, nowadays it seems Ruby has a reasonably large number of employment opportunities. The latest version of Ruby is 2.5.3 (it was released on October 18, 2018). In the present article I create a simple Message Board App using Ruby and PostgreSQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aOC-bmm8NCD_ozXV" /><figcaption>Photo by <a href="https://unsplash.com/@ninjason?utm_source=medium&amp;utm_medium=referral">Jason Leung</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I’ve found the following book very helpful for understanding the basics of the language. I will use Sinatra framework in this article.</p><p><a href="https://www.learnenough.com/ruby-tutorial-tutorial/hello_world/ruby_repl">Learn Enough Ruby to Be Dangerous</a></p><blockquote><em>Keywords: Ruby, Embedded Ruby, HTML, CSS, SQL, erb, Sinatra, PostgreSQL, Linux, Ubuntu, rerun, Message Board, yield, HTTP, regular expressions, regex</em></blockquote><blockquote><strong><em>DISCLAIMER: THE VIEWS AND OPINIONS EXPRESSED IN THIS ARTICLE ARE THOSE OF THE AUTHOR AND DO NOT REFLECT THE OFFICIAL POLICY OR POSITION OF THE EMPLOYER OF THE AUTHOR. THE ARTICLE IS NOT ENDORSED BY, DIRECTLY AFFILIATED WITH, MAINTAINED, AUTHORIZED, OR SPONSORED BY ANY CORPORATION OR ORGANIZATION. THE INFORMATION CONTAINED ON THIS ARTICLE IS INTENDED SOLELY TO PROVIDE GENERAL GUIDANCE ON MATTERS OF INTEREST FOR THE PERSONAL USE OF THE READER, WHO ACCEPTS FULL RESPONSIBILITY FOR ITS USE. ALTHOUGH THE AUTHOR HAS MADE EVERY EFFORT TO ENSURE THAT THE INFORMATION IN THIS ARTICLE WAS CORRECT AT THE TIME OF THE WRITING, THE AUTHOR DOES NOT ASSUME AND HEREBY DISCLAIM ANY LIABILITY TO ANY PARTY FOR ANY LOSS, DAMAGE, OR DISRUPTION CAUSED BY ERRORS OR OMISSIONS, WHETHER SUCH ERRORS OR OMISSIONS RESULT FROM NEGLIGENCE, ACCIDENT, OR ANY OTHER CAUSE.</em></strong></blockquote><h3>Table of Content</h3><p>The app will be built step by step. The article is divided into the following sections:</p><ul><li>Prerequisites</li><li>Preparation</li><li>Message Board Web App</li><li>1st step: List hard-coded values</li><li>2nd step: Read messages from the db</li><li>3rd step: Enable posting of messages and save them in the database</li><li>Useful links for further reading</li><li>Enhancing the Hello World example</li><li>Closing words</li><li>References</li></ul><h3>Prerequisites</h3><p>For this article I will use the following programming languages and technology:</p><ul><li>HTML</li><li>CSS</li><li>Ruby</li><li>SQL</li><li>Sinatra (Ruby library)</li><li>PostgreSQL</li><li>Linux</li></ul><h3>Preparation</h3><p>This step is about:</p><ul><li>installing Sinatra for Ruby</li><li>testing Ruby with a simple hello world app</li><li>starting PostgreSQL server</li><li>installing rerun for Ruby (rerun is a Ruby library)</li></ul><h4>Installing Sinatra</h4><p>I assume that your system already contains Ruby. I use Ubuntu 14.04.5 LTS (trusty) and my version of Ruby is</p><pre>ruby 2.4.0p0 (2016-12-24 revision 57164) [x86_64-linux]</pre><p>I use <a href="https://c9.io/">Cloud 9</a> environment.</p><p>For these examples we will also need <a href="http://sinatrarb.com/">Sinatra</a>. Sinatra is a Domain Specific Language for quickly creating web applications in Ruby with minimal effort. To check if Sinatra is already installed, you can use</p><pre>gem list sinatra</pre><p>It should return something like this, containing the version of Sinatra installed in your system:</p><pre>*** LOCAL GEMS ***</pre><pre>sinatra (2.0.4)</pre><p>If Sinatra is not installed, you should install it:</p><pre>gem install sinatra</pre><p>To try if everything works, create the following Ruby file. Ruby source code has the extension .rb.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e81045f68a7312d9e18e3310563b147/href">https://medium.com/media/0e81045f68a7312d9e18e3310563b147/href</a></iframe><p>Run this file with Ruby:</p><pre>ruby ruby-hello-world-sinatra.rb</pre><p>In my system the command returns the following. This will start a web server and run the Ruby script.</p><pre>nlharri:~/workspace/ruby $ ruby ruby-hello-world-sinatra.rb <br>[2018-11-21 09:53:58] INFO  WEBrick 1.3.1<br>[2018-11-21 09:53:58] INFO  ruby 2.4.0 (2016-12-24) [x86_64-linux]<br>== Sinatra (v2.0.4) has taken the stage on 8080 for development with backup from WEBrick<br>[2018-11-21 09:53:58] INFO  WEBrick::HTTPServer#start: pid=2433 port=8080</pre><p>Open your web browser and go to <a href="http://localhost:8080,">http://localhost:8080</a>. You need to see a hello world text in the browser.</p><p>To stop the server, press CTRL+C in the terminal. I will get back to the hello world example later.</p><h4>Start PostgreSQL server</h4><p>I will use PostgreSQL version 9.3.18. If PostgreSQL server is not starting automatically, and you would like to start it, you can use</p><pre>sudo update-rc.d postgresql enable</pre><p>If you would like to start the PostgreSQL server, you can use</p><pre>sudo service postgresql start</pre><p>By default, PostgreSQL sets up the user and database “postgres” upon a new installation. We interact with the postgres database software through an interface called “psql.”</p><p>You can login with user “postgres” to database “postgres” with the following command:</p><pre>sudo -u postgres psql postgres</pre><p>(You can exit with CTRL+D.)</p><h4>Install rerun</h4><p>We will install rerun, which will make it possible to make changes to the code and see the results without restarting the server.</p><p>For this, we prepare a Gemfile in the project.</p><pre>touch Gemfile</pre><p>And the Gemfile should contain the following:</p><pre>source &#39;<a href="https://rubygems.org&/#39;">https://rubygems.org&#39;</a></pre><pre>gem &#39;sinatra&#39;, &#39;2.0.4&#39;<br>gem &#39;rerun&#39;,   &#39;0.13.0&#39;</pre><p>We need to install these packages (we already installed sinatra earlier).</p><pre>bundle install</pre><p>(If the system does not contain bundler, you need to install it with sudo gem install bundler)</p><p>Now we need to start the server, but for this we use the following command:</p><pre>bundle exec rerun ruby-hello-world-sinatra.rb</pre><p>Earlier we needed to quit and restart the server in order to see changes to the app, but thanks to the rerun the app is updated automatically, after we refresh the browser by hand.</p><h3>Message Board Web App</h3><p>What will the app know? The app will show the already posted messages, and the nickname of the person who posted the message. It will allow to post new messages. The data will be stored in a database, and the app will read the entries from the database, and save the new posts there.</p><p>The app is created step by step.</p><h3>1st step: List hard-coded values</h3><p>The first version of the app will show some hard-coded messages without using the database. (Later we will enhance the app to read up messages from the database.) In the first version we will also not able to post messages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ciHqWqS9gPwkHGmfLtU3MA.jpeg" /></figure><h4>Design</h4><p>I tried to define a nice-looking but simple design with CSS. I used Bubbly example which was very helpful for me to define the design.</p><p><a href="https://leaverou.github.io/bubbly/">Bubbly</a></p><p>The basic layout and design looks like the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*sSEWSIwswlFM0BlFd6ANcw.png" /></figure><p>I also put this to codepen.io.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fnlharri%2Fembed%2Fpreview%2FxQjGrr%3Fheight%3D600%26slug-hash%3DxQjGrr%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Fnlharri%2Fpen%2FxQjGrr&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F1906673.xQjGrr.small.d3fc5b4d-bbd4-4732-96a3-25c2ab952a3c.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/d208aff836e815a01287007c0c994fb2/href">https://medium.com/media/d208aff836e815a01287007c0c994fb2/href</a></iframe><h4>Implementation with Embedded Ruby</h4><p>We will hard-code values of the messages data, and use templating of Sinatra to show the data. The data is passed to the erb, for which <a href="https://stackoverflow.com/questions/6737889/passing-parameters-to-erb-view">this stackoverflow post</a> was very useful to understand.</p><p><a href="https://gist.github.com/nlharri/5ce357f60b3208aa04f359bf56559474">Here</a> you can check the coding. The l_main.erb and the v_message.erb should be in the views folder so that Sinatra will find them.</p><p>With :locals we can pass data to the erb.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72eadb2596b2201c5c281847c1566e37/href">https://medium.com/media/72eadb2596b2201c5c281847c1566e37/href</a></iframe><h3>2nd step: Read messages from the db</h3><p>In this step we enhance the app to read the messages from the db. For this we need to define a database and a table, and put some entries to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qrTymYH0hJuSy1-Z" /><figcaption>Photo by <a href="https://unsplash.com/@beautyoftechnology?utm_source=medium&amp;utm_medium=referral">Nikolay Tarashchenko</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Define database and table</h4><p>For the next version of the app we need a database to store the data.</p><p>For this step the following tutorials were very useful.</p><ul><li><a href="https://www.digitalocean.com/community/tutorials/how-to-create-remove-manage-tables-in-postgresql-on-a-cloud-server">How To Create, Remove, &amp;amp; Manage Tables in PostgreSQL on a Cloud Server | DigitalOcean</a></li><li><a href="http://zetcode.com/db/postgresqlruby/">PostgreSQL Ruby tutorial</a></li></ul><p>In this step we will:</p><ul><li>create a new user messageboarduser in the system for accessing the database</li><li>create a new user messageboarduser in PostgreSQL</li><li>define database messageboard</li><li>define database table messageboardmessages</li></ul><h4>Create a new user in the system</h4><p>We create a new user with the following command</p><pre>sudo adduser messageboarduser</pre><p>You need to provide a password. (I used messageboarduser also for the password, but of course you should not do the same in a productive environment.)</p><h4>Create a new user and database in PostgreSQL</h4><p>Log into the default PostgreSQL user (called “postgres”) to create a database and assign it to the new user:</p><pre>sudo su - postgres<br>psql</pre><p>Create a new user that matches the system user you created. Then create a database managed by that user:</p><pre>CREATE USER messageboarduser WITH PASSWORD &#39;messageboarduser&#39;;<br>CREATE DATABASE messageboard OWNER messageboarduser;</pre><p>Exit out of the interface with the following command:</p><pre>\q</pre><p>Exit out of the default “postgres” user account and log into the user you created with the following commands:</p><pre>exit<br>sudo su - messageboarduser</pre><p>Sign into the database you created with the following command:</p><pre>psql messageboard</pre><h4>Define database table for the app</h4><p>We will define the messageboardmessages db table with the following command:</p><pre>CREATE TABLE messageboardmessages (<br> message_id varchar(36) PRIMARY KEY,<br> nickname varchar(30) NOT NULL,<br> message varchar(200) NOT NULL,<br> timestamp varchar(50) NOT NULL<br>);</pre><p>We can see the new table by typing “\d” into the prompt:</p><pre>\d</pre><p>The result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*mdm4kXdDEPhnbQiJQ2IDIQ.png" /></figure><p>The following command prints the definition of the table</p><pre>\d messageboardmessages</pre><p>The result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*BA1eAKrgfvW-KgTJF1e-cA.png" /></figure><h4>Add entries to the table</h4><p>We will add one sample entry to the newly defined table. (Here the value of message_id is a unique identifier which I generated manually. We will get back to unique identifier generation later.)</p><pre>INSERT INTO messageboardmessages(message_id, nickname, message) <br>VALUES (&#39;201519e8-f3e7-4fcf-9349-3f81b94e908c&#39;, &#39;PostgreSQLUser&#39;, &#39;Hello from PostgreSQL&#39;, &#39;2018-11-30 10:48:19 +0000&#39;);</pre><p>Let’s query the data to see if it is really there:</p><pre>SELECT * FROM messageboardmessages;</pre><p>The result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*AHQSyEEj0NU0i5BWKMfa6Q.png" /></figure><p>So we have the entry there.</p><h4>Check adjust PostgreSQL config file (optional)</h4><p>It might happen that when working on a Linux machine of the Ubuntu flavor and setting up a PostgreSQL 9.3 database, you run into the error <strong><em>‘PG::ConnectionBad: FATAL: Peer authentication failed for user’</em></strong> when trying to connect to a database from a web application. The most common fix for this error in a development or staging environment is to loosen the local permissions up a bit. For this you need to follow the following tutorial.</p><p><a href="https://memorytin.com/2016/04/12/postgresql-database-pgconnectionbad-fatal-peer-authentication-failed-for-user/">PostgreSQL Database: PG::ConnectionBad: FATAL: Peer authentication failed for user</a></p><ul><li>locate the file /etc/postgresql/9.3/main/pg_hba.conf and open it using sudo (sudo nano /etc/postgresql/9.3/main/pg_hba.conf)</li><li>scroll down through the file (almost to the bottom) until you find the section that starts with #Database administrative login by Unix domain socket</li><li>directly below that you will find local all all peer or local all postgres peer — change it to local all all trust</li><li>save and close the file</li><li>restart the PostgreSQL server: sudo service postgresql restart</li></ul><h4>Enhance the app with reading from the db</h4><p>For this we need the pg Gem. Let’s enhance the Gemfile with this. So the Gemfile looks like this:</p><pre>source &#39;<a href="https://rubygems.org&/#39;">https://rubygems.org&#39;</a></pre><pre>gem &#39;sinatra&#39;, &#39;2.0.4&#39;<br>gem &#39;rerun&#39;,   &#39;0.13.0&#39;<br>gem &#39;pg&#39;,      &#39;1.1.3&#39;</pre><p>Install the Gem:</p><pre>bundle install</pre><p>We need to include pg in the app.rb to use it.</p><pre>require &#39;pg&#39;</pre><p>We will also need to enhance the get &#39;/&#39; do part to query the data from the database. The final version of app.rb can be seen here:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b4078bd49879b86eebad17548af3abb/href">https://medium.com/media/0b4078bd49879b86eebad17548af3abb/href</a></iframe><p>After this modification, when the server is restarted and the page is reloaded, you should see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*_k-OS-HAWHQ5ZaR9XrNLjQ.png" /></figure><h3>3rd step: Enable posting of messages and save them in the database</h3><p>This step is about:</p><ul><li>generating unique identifiers</li><li>validate input</li><li>generate time stamp</li><li>writing data to the database</li></ul><h4>Generating unique identifiers</h4><p>Enhance the Gemfile with uuidtools:</p><pre>source &#39;<a href="https://rubygems.org&/#39;">https://rubygems.org&#39;</a></pre><pre>gem &#39;sinatra&#39;, &#39;2.0.4&#39;<br>gem &#39;rerun&#39;,   &#39;0.13.0&#39;<br>gem &#39;pg&#39;, &#39;1.1.3&#39;<br>gem &#39;uuidtools&#39;, &#39;2.1.5&#39;</pre><p>This uuidtools package can be used to generate a new unique identifier for the new message entry.</p><p>The main app.rb will be enhanced with the generation of the new identifier.</p><h4>Validation of input to avoid SQL injection</h4><p>We need to avoid SQL injection, therefore we allow only a limited set of characters to be used in the input fields. For this we will use a regular expression check, similar to the following:</p><pre>if ( input =~ /<strong>^[a-zA-Z0-9 ]*$</strong>/ ) <br> puts &quot;input is OK!&quot; <br>end</pre><p>This will allow using only characters of the English alphabet, numbers, and space.</p><p>This is just an example for the app, and in a productive environment you should use more robust techniques to avoid SQL injection!</p><p>Regular expression tester for Ruby:</p><p><a href="http://rubular.com/">Rubular: a Ruby regular expression editor and tester</a></p><p>A good guide to regular expressions can be found here:</p><p><a href="https://www.tutorialspoint.com/ruby/ruby_regular_expressions.htm">Ruby - Regular Expressions</a></p><p>Guides about SQL injections regarding Ruby can be found here:</p><ul><li><a href="https://blog.sqreen.io/preventing-sql-injections-in-ruby/">Preventing SQL injections in Ruby (and other vulnerabilities) - Sqreen Blog | Modern Application Security</a></li><li><a href="http://gavinmiller.io/2015/fixing-sql-injection-vulnerabilities/">Fixing SQL Injection Vulnerabilities in Ruby/Rails</a></li><li><a href="https://rails-sqli.org/">Rails SQL Injection Examples</a></li></ul><h4>Generating time stamp</h4><p>For the timestamp generation we will use default feature of Ruby:</p><pre>timestamp = Time.now</pre><p>Note that in this example we use the time of the server. This will be saved in the database, and not the time on the clients’ computer.</p><h4>Writing the data to the database</h4><p>Database insertion will be done with the following implementation:</p><pre># connect to the database<br>connection = PG.connect :dbname =&gt; &#39;messageboard&#39;, :user =&gt; &#39;messageboarduser&#39;, :password =&gt; &#39;messageboarduser&#39;<br>  <br># generate new UUID<br>val_uuid = UUIDTools::UUID.random_create.to_s<br>  <br># insert data into the database<br>timestamp = Time.now<br>connection.exec &quot;INSERT INTO messageboardmessages(message_id, nickname, message, timestamp) VALUES (&#39;#{val_uuid}&#39;, &#39;#{params[:nickname]}&#39;, &#39;#{params[:message]}&#39;, &#39;#{timestamp}&#39;);&quot;</pre><h4>Summary of the 3rd step</h4><p>We needed to modify:</p><ul><li>Gemfile</li><li>app.rb</li><li>main.css</li><li>l_main.erb</li><li>v_message.erb</li></ul><p>In this example implementation there are many repetitions. According to the <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a> principle we should eliminate repetitions. I need to refactor this code later. In this example I just would like to show a quick example of using Ruby and Sinatra.</p><p>The modified implementation looks like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e23dbc9ca72db638f6bd0ce688244df/href">https://medium.com/media/2e23dbc9ca72db638f6bd0ce688244df/href</a></iframe><h3>Useful links for further reading</h3><ul><li><a href="https://www.postgresql.org/download/linux/ubuntu/">Linux downloads (Ubuntu)</a></li><li><a href="https://wiki.postgresql.org/wiki/Apt">Apt - PostgreSQL wiki</a></li><li><a href="https://stackoverflow.com/questions/5658702/ruby-postgresql-tutorials">Ruby PostgreSQL tutorials</a></li></ul><h3>Enhancing the Hello World example</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yOBnrSC2BTAJVscG" /><figcaption>Photo by <a href="https://unsplash.com/@rawpixel?utm_source=medium&amp;utm_medium=referral">rawpixel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Now we will enhance the Hello World example. The following shows using the yield statement.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b58721c769d49f7f0fe427b825c38e5c/href">https://medium.com/media/b58721c769d49f7f0fe427b825c38e5c/href</a></iframe><p>The tag function will wrap the provided text with the provided HTML tag name. With Sinatra, we provided this markup text to the output when the root of the website is accessed by the client.</p><p>We created another function, day_of_the_week, to get the name of the day of the week. For this we use the built-in date library of Ruby.</p><h3>Closing words</h3><p>I hope you have learned something new today. Thank you for reading this article.</p><p>The Message Board App can be accessed in my Github repo.</p><p><a href="https://github.com/nlharri/RubyMessageBoard">nlharri/RubyMessageBoard</a></p><h3>References</h3><ul><li><a href="https://www.learnenough.com/">Learn Enough to Be Dangerous</a></li><li><a href="https://www.ruby-lang.org/en/">Ruby Programming Language</a></li><li><a href="https://www.postgresql.org/">PostgreSQL</a></li><li><a href="https://github.com/sinatra/sinatra">GitHub - sinatra/sinatra: Classy web-development dressed in a DSL (official / canonical repo)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ff2610c85e4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thecodinghype/experimenting-with-ruby-sinatra-and-postgresql-a-message-board-app-4ff2610c85e4">Experimenting with Ruby, Sinatra and PostgreSQL: a Message Board App</a> was originally published in <a href="https://medium.com/thecodinghype">The Coding Hype</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reactive Programming in Javascript using RxJS]]></title>
            <link>https://medium.com/thecodinghype/reactive-programming-in-javascript-using-rxjs-3b05e186c115?source=rss----9fceaf0f32f4---4</link>
            <guid isPermaLink="false">https://medium.com/p/3b05e186c115</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[npm]]></category>
            <dc:creator><![CDATA[László Harri Németh]]></dc:creator>
            <pubDate>Tue, 11 Dec 2018 09:01:01 GMT</pubDate>
            <atom:updated>2018-12-11T09:01:00.895Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B9VWf6uFISQxhMBn" /><figcaption>Photo by <a href="https://unsplash.com/@s_sagano?utm_source=medium&amp;utm_medium=referral">Sora Sagano</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Nowadays there is a hype around reactive programming. This article explains the motivation behind learning reactive programming, and the basic concepts to get started.</p><p>In this article I use Node.js as a runtime environment for learning RxJS.</p><blockquote><em>Keywords: Node.js, NPM, Javascript, RxJS, Linux, Ubuntu, NVM, ReactiveX, Reactive Programming, Stream, Observable, Observer, Subscription, Operator, Subject, filter, map, pipe, scan, reduce, throttleTime, unsubscribe</em></blockquote><blockquote><strong><em>DISCLAIMER: THE VIEWS AND OPINIONS EXPRESSED IN THIS ARTICLE ARE THOSE OF THE AUTHOR AND DO NOT REFLECT THE OFFICIAL POLICY OR POSITION OF THE EMPLOYER OF THE AUTHOR. THE ARTICLE IS NOT ENDORSED BY, DIRECTLY AFFILIATED WITH, MAINTAINED, AUTHORIZED, OR SPONSORED BY ANY CORPORATION OR ORGANIZATION. THE INFORMATION CONTAINED ON THIS ARTICLE IS INTENDED SOLELY TO PROVIDE GENERAL GUIDANCE ON MATTERS OF INTEREST FOR THE PERSONAL USE OF THE READER, WHO ACCEPTS FULL RESPONSIBILITY FOR ITS USE. ALTHOUGH THE AUTHOR HAS MADE EVERY EFFORT TO ENSURE THAT THE INFORMATION IN THIS ARTICLE WAS CORRECT AT THE TIME OF THE WRITING, THE AUTHOR DOES NOT ASSUME AND HEREBY DISCLAIM ANY LIABILITY TO ANY PARTY FOR ANY LOSS, DAMAGE, OR DISRUPTION CAUSED BY ERRORS OR OMISSIONS, WHETHER SUCH ERRORS OR OMISSIONS RESULT FROM NEGLIGENCE, ACCIDENT, OR ANY OTHER CAUSE.</em></strong></blockquote><h3>Table of Content</h3><p>The article is divided into the following sections:</p><ul><li>Motivation and basics</li><li>Required knowledge</li><li>What is RxJS?</li><li>Fundamental concepts in RxJS</li><li>Preparation of runtime environment</li><li>Observable, Observer and Subscribe</li><li>Further Observable Creation Possibilities</li><li>Operators: Filter and Map</li><li>About the pipe</li><li>Further operators: scan and reduce</li><li>About throttleTime</li><li>Unsubscription with unsubscribe</li><li>Closer to the web</li><li>Conclusion</li><li>Resources</li></ul><h3>Motivation and basics</h3><p>Todays highly interactive web applications and mobile apps the handling of user interface interactions is crucial. We can imagine the UI interactions as a series of events, or in other words, a stream of events. We can think of an event as a piece of information (data), which is available at a certain point in time. For example, a mouse click event happens when the user clicks with the mouse, and the data which is related to this event are the coordinates of the mouse pointer, when the click happens.</p><p>There are some fundamental concepts related to reactive programming, which are described in the following chapter.</p><p>For this tutorial I use RxJS, which is a Javascript library for reactive programming. Therefore the concepts described in this tutorial are the ones used by RxJS.</p><h3>Required knowledge</h3><p>In order to understand this article you need to have at least basic knowledge of the following:</p><ul><li>Javascript</li><li>Node.js</li><li>Node Package Manager (npm)</li></ul><ul><li><a href="https://www.w3schools.com/js/default.asp">W3Schools.com</a></li><li><a href="https://www.w3schools.com/nodejs/default.asp">Node.js Tutorial</a></li><li><a href="https://www.sitepoint.com/beginners-guide-node-package-manager/">A Beginner&#39;s Guide to npm - the Node Package Manager - SitePoint</a></li></ul><h3>What is RxJS?</h3><p>RxJS is a Javascript library licensed under Apache-2.0 License. It is part of ReactiveX, which is a collection of open source projects. On the website of RxJS we can read the following definition.</p><blockquote>RxJS is a library for reactive programming using Observables, to make it easier to compose asynchronous or callback-based code. This project is a rewrite of Reactive-Extensions/RxJS with better performance, better modularity, better debuggable call stacks, while staying mostly backwards compatible, with some breaking changes that reduce the API surface. — RxJS (<a href="https://rxjs-dev.firebaseapp.com/">https://rxjs-dev.firebaseapp.com/</a>)</blockquote><p>RxJS stands for <strong>R</strong>eactive E<strong>x</strong>tensions for <strong>J</strong>ava<strong>s</strong>cript.</p><h3>Fundamental concepts in RxJS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7CXF1Lkgm9et5OhV" /><figcaption>“blue ballpoint pen on white notebook” by <a href="https://unsplash.com/@medbadrc?utm_source=medium&amp;utm_medium=referral">Med Badr Chemmaoui</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The following concepts are very important to understand if we would like to learn RxJS:</p><ul><li><strong>Stream</strong>: A stream is a sequence of data elements made available over time. A stream can be thought of as items on a conveyor belt being processed one at a time rather than in large batches. (<a href="https://en.wikipedia.org/wiki/Stream_(computing)">Wikipedia</a>)</li><li><strong>Observable</strong>: RxJS represents asynchronous data streams using observable sequences. These observable sequences are called Observables. Observables can be used using push or pull patterns. (<a href="https://medium.com/google-developer-experts/angular-introduction-to-reactive-extensions-rxjs-a86a7430a61f">Source</a>)</li><li><strong>Observer</strong>: According to the definition, Observer is an interface for a consumer of push-based notifications delivered by an Observable. An <a href="http://reactivex.io/rxjs/class/es6/MiscJSDoc.js~ObserverDoc.html">Observer</a> is a consumer of values delivered by an Observable. Observers are objects with three callbacks, one for each type of notification that an Observable may deliver: next, error, and complete. (<a href="https://github.com/ReactiveX/rxjs/blob/master/doc/observer.md">Source</a>).</li><li><strong>Subscription</strong>: <a href="http://reactivex.io/documentation/operators/subscribe.html">Subscribe </a>is an operator. The Subscribe operator is the glue that connects an Observer to an Observable. In order for an Observer to see the items being emitted by an Observable, or to receive error or completed notifications from the Observable, it must first subscribe to that Observable with this operator.</li><li><strong>Operator</strong>: Operators are methods that you can use on Observables (and Subjects) that allow you to change the original observable in some manner and return a new observable (<a href="https://coursetro.com/posts/code/150/RxJS-Operators-Tutorial---Learn-How-to-Transform-Observables">Source</a>). Subscribe is an operator.</li><li><strong>Subject</strong>: An RxJS Subject is a special type of Observable that allows values to be multicasted to many Observers. While plain Observables are unicast (each subscribed Observer owns an independent execution of the Observable), Subjects are multicast. A Subject is like an Observable, but can multicast to many Observers. (<a href="https://github.com/ReactiveX/rxjs/blob/master/doc/subject.md">Source</a>)</li></ul><p>Further reading:</p><ul><li><a href="https://en.wikipedia.org/wiki/Stream_(computing)">Stream (computing) - Wikipedia</a></li><li><a href="https://medium.com/google-developer-experts/angular-introduction-to-reactive-extensions-rxjs-a86a7430a61f">Angular — Introduction to Reactive Extensions (RxJS)</a></li><li><a href="http://reactivex.io/rxjs/class/es6/MiscJSDoc.js~ObserverDoc.html">Observer | RxJS API Document</a></li><li><a href="http://reactivex.io/documentation/operators/subscribe.html">Subscribe</a></li><li><a href="https://coursetro.com/posts/code/150/RxJS-Operators-Tutorial---Learn-How-to-Transform-Observables">RxJS Operators Tutorial - Learn How to Transform Observables</a></li></ul><p><strong>Observer</strong>: <a href="https://raw.githubusercontent.com/ReactiveX/rxjs/master/doc/observer.md">https://raw.githubusercontent.com/ReactiveX/rxjs/master/doc/observer.md</a></p><p><strong>Subject</strong>: <a href="https://github.com/ReactiveX/rxjs/blob/master/doc/subject.md">https://github.com/ReactiveX/rxjs/blob/master/doc/subject.md</a></p><h3>Preparation of runtime environment</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6EIJKjDzjH-p-hoR" /><figcaption>“grayscale photography of piled racks” by <a href="https://unsplash.com/@ripato?utm_source=medium&amp;utm_medium=referral">Ricardo Gomez Angel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As the runtime environment for the examples I use Ubuntu 14.04.5 LTS (trusty). I used Node.js version v6.11.2. My NPM version is 3.10.10. I assume that Node.js and npm is already installed in your system, and a new folder was created for these rxjs examples. In my system I named this folder workspace.</p><p>(In my system, Node Version Manager (nvm) is also installed (version 0.31.0). NVM is a powerful tool to manage multiple Node.js versions in your development environment. for further info about NVM you can check for example <a href="https://nodesource.com/blog/installing-node-js-tutorial-using-nvm-on-mac-os-x-and-ubuntu/">https://nodesource.com/blog/installing-node-js-tutorial-using-nvm-on-mac-os-x-and-ubuntu/</a>)</p><p>The following steps are required to initialize our runtime environment:</p><ol><li><strong>initalize the folder by generating a new </strong><strong>package.json file</strong> (The reason behind creating this file can be read at <a href="https://docs.npmjs.com/creating-a-package-json-file">https://docs.npmjs.com/creating-a-package-json-file</a>):</li></ol><pre>npm init -y</pre><p>After this we see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*QI2RI2MLH6FU9F8Y4QU1Hg.png" /></figure><p>2. <strong>install RxJS and other dependencies with the following command</strong>:</p><pre>npm install rxjs</pre><p>After this step our folder looks like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*loZ_pQR5vyzEOXH08mOikA.png" /></figure><p>The folder node_modules contains the installed Node.js modules.</p><p>3. <strong>Test if RxJS is really working</strong>. This is done by our first simple Javascript which looks like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/daad20e22f2f5efc6c1313c5a3441a71/href">https://medium.com/media/daad20e22f2f5efc6c1313c5a3441a71/href</a></iframe><p>You can copy-paste this code to your own file, by starting the nano editor from the console:</p><pre>nano rxjs-helloworld.js</pre><p>In nano, you can save the file by pressing CTRL+O and ENTER. You can exit from nano by pressing CTRL+X.</p><p>To run the script you can use the following command:</p><pre>node rxjs-helloworld.js</pre><p>Or, if you don’t have the current directory in your path, you need to use</p><pre>node ./rxjs-helloworld.js</pre><p>The output looks like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*rzkET24kgCK9ezk7SrB8Og.png" /></figure><p>With this we have prepared our environment for trying out RxJS. The Hello World example will be explained later in this article. Remember that you can always run your code with</p><pre>node my_script.js</pre><h3>Observable, Observer and Subscribe</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FVKZpWwO9gwGi6cw" /><figcaption>Photo by <a href="https://unsplash.com/@jantined?utm_source=medium&amp;utm_medium=referral">Jantine Doornbos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s look at the first example we have already seen.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/daad20e22f2f5efc6c1313c5a3441a71/href">https://medium.com/media/daad20e22f2f5efc6c1313c5a3441a71/href</a></iframe><p>In this example</p><ol><li>We define an observable with Observable.create(). In the input of this function call we specify a callback function, which receives observer as the parameter, and calls functions on this. The next function is called 3 times, and the complete function once.</li><li>Then we call subscribemethod of the observable.</li></ol><p>The <a href="http://reactivex.io/rxjs/class/es6/MiscJSDoc.js~ObserverDoc.html">Observer</a> has 3 methods:</p><ul><li><strong>next</strong>: The callback to receive notifications of type next from the Observable, with a value.</li><li><strong>error</strong>: The callback to receive notifications of type error from the Observable, with an attached Error. (More info about the error object <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error">here</a>)</li><li><strong>complete</strong>: The callback to receive a valueless notification of type complete from the Observable.</li></ul><p>In the subscribe method of the observable we specify 3 callback functions as parameters. The first one is called when the next data is emitted by the observable, the second one is called when an error occurs, the third one is called when the observer completes its job, and there was no error.</p><p>The subscribe can be called also in different way, by specifying an object with 3 properties, like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3fa1260133414c42a100363a21dc073/href">https://medium.com/media/a3fa1260133414c42a100363a21dc073/href</a></iframe><h3>Further Observable Creation Possibilities</h3><p>Observables can be created from different objects.</p><p>In the following example, observable is created out of an array of numbers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce7f9d94ab0e7bd75b1a8102bffd2804/href">https://medium.com/media/ce7f9d94ab0e7bd75b1a8102bffd2804/href</a></iframe><p>Here, in case of specifying this callback function in the subscribe, we could also say:</p><pre>observableFromArray.subscribe({<br>  next: function(value) { console.log(value); }<br>});</pre><p>It’s also fine that we don’t specify the error and the complete attributes.</p><p>We can convert strings as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8450586cba44affc1564ea90b86f57bc/href">https://medium.com/media/8450586cba44affc1564ea90b86f57bc/href</a></iframe><p>We can create observable from events as well. For this, in Node environment, we need an event emitter. (Node.js contains event emitters by default, you can read more about this <a href="https://nodejs.org/api/events.html#events_class_eventemitter">here</a>.)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfa994f07361b816c84899529e854afb/href">https://medium.com/media/dfa994f07361b816c84899529e854afb/href</a></iframe><h3>Operators: filter and map</h3><p>Observables can be transformed to other Observables. This can be done by using operators. Examples of operators:</p><ul><li>from</li><li>fromEvent</li><li>filter</li><li>map</li></ul><p>There are plenty of operators, the list can be found <a href="https://www.learnrxjs.io/operators/">here</a>.</p><p>In the following example, filter call filters out the even numbers from the stream, and returns a stream which contains only the odd numbers x % 2 will be 0 in case of even numbers, and 1 in case of odd numbers. 1 is truthy, therefore the odd numbers will remain in the stream. After this we subscribe to the stream to print it out to the console.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d7d3e4fda03fd64b20385abcca6f1f0/href">https://medium.com/media/0d7d3e4fda03fd64b20385abcca6f1f0/href</a></iframe><p>We enhance this example by a map function, which doubles the emitted numbers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5e3d4ecd1874b4fa67d1830579d93fa/href">https://medium.com/media/a5e3d4ecd1874b4fa67d1830579d93fa/href</a></iframe><p>The output of this second example will be:</p><pre>Next: 2<br>Next: 6<br>Next: 10<br>Next: 14<br>Next: 18</pre><h3>About the pipe</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4RSJygTBS6NNHgYn" /><figcaption>Photo by <a href="https://unsplash.com/@samthewam24?utm_source=medium&amp;utm_medium=referral">Samuel Sianipar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the above examples we used pipe(). In RxJS operators are pure functions. This means that they can be chained, and this chaining is done by using pipe() function on the observable. More info about piping can be found <a href="https://blog.hackages.io/rxjs-5-5-piping-all-the-things-9d469d1b3f44">here</a>.</p><h3>Further operators: scan and reduce</h3><p>The signature of scan operator looks like the <a href="https://www.learnrxjs.io/operators/transformation/scan.html">following</a>:</p><p>scan(accumulator: function, seed: any): Observable</p><p>Scan will call the accumulator function on the values over time, starting with value of seed as a basis.</p><p>In this example we calculate the factorial of numbers from 1 to 10.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e77912009207fc32f981789e4ca53c79/href">https://medium.com/media/e77912009207fc32f981789e4ca53c79/href</a></iframe><p>The output is:</p><pre>1<br>2<br>6<br>24<br>120<br>720<br>5040<br>40320<br>362880<br>3628800</pre><p>Reduce is something similar, but it reduces the values to a single value in each call.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70fbb949b3ad7da594e5432cd5c01386/href">https://medium.com/media/70fbb949b3ad7da594e5432cd5c01386/href</a></iframe><p>The output is: 3628800</p><h3>About throttleTime</h3><p>The definition of throttleTime() is quite simple: Emit latest value when specified duration has passed (<a href="https://www.learnrxjs.io/operators/filtering/throttletime.html">source</a>). What does this mean?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a741cf4d990629829e9166eb03f270c9/href">https://medium.com/media/a741cf4d990629829e9166eb03f270c9/href</a></iframe><p>The result of the above code will be the following:</p><pre>0<br>2<br>4<br>6<br>8<br>10<br>12<br>14<br>16<br>18<br>20<br>22<br>24<br>&lt;...and the sequence goes on&gt;</pre><p>The interval(500) method emits a value every 500 milliseconds. The throttleTime(1000) method gets the latest value from the sequence every 1000 milliseconds (=1 second).</p><h3>Unsubscription with unsubscribe</h3><p>Let’s enhance the above example with an unsubscribe() call:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eddfda5d06f7aad4f99fce691bb27b52/href">https://medium.com/media/eddfda5d06f7aad4f99fce691bb27b52/href</a></iframe><p>This will result in:</p><pre>0<br>2<br>4<br>6<br>8<br>10<br>12<br>14<br>16<br>18</pre><p>After 10 seconds the sequence stops.</p><h3>Closer to the web</h3><p>The last example below uses an HTML page with Javascript to try RxJS. The page shows a button, and when you click the button, it will show the current time. For this example I used another JS library: moment.js, for converting the time to the format I would like to see.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07022dfe82d1dae503470e7089c5a3dc/href">https://medium.com/media/07022dfe82d1dae503470e7089c5a3dc/href</a></iframe><p>I also put this on Codepen so that you can try it.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fnlharri%2Fembed%2Fpreview%2FzMdzXd%3Fheight%3D600%26slug-hash%3DzMdzXd%26default-tabs%3Dhtml%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Fnlharri%2Fpen%2FzMdzXd&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddff7c20c6aba8a26ba8143a97deb664/href">https://medium.com/media/ddff7c20c6aba8a26ba8143a97deb664/href</a></iframe><h3>Conclusion</h3><p>This was a quick overview of RxJS, which definitely worth to dig deeper in it. It absolutely makes sense these days to learn it.</p><p>I hope you learned something new today. If you have any questions please leave a comment.</p><h3>Resources</h3><p>There are plenty of resources on the web regarding reactive programming. For this tutorial I used the following:</p><ul><li><a href="https://codingthesmartway.com/getting-started-with-rxjs-part-1-setting-up-the-development-environment-creating-observables/">Getting Started With RxJS - Part 1: Setting Up The Development Environment &amp; Creating Observables</a></li><li><a href="https://medium.com/google-developer-experts/angular-introduction-to-reactive-extensions-rxjs-a86a7430a61f">Angular — Introduction to Reactive Extensions (RxJS)</a></li><li><a href="https://medium.com/@mohandere/rxjs-5-in-5-minutes-1c3b4ed0d8cc">Rxjs: In 5 minutes!</a></li><li><a href="https://medium.com/corebuild-software/why-you-should-learn-reactive-programming-51b6ffc31425">Why you should learn Reactive Programming</a></li><li><a href="https://reactive.how/">RxJS and Reactive Programming - Animations and visual lessons</a></li><li><a href="https://rxjs-dev.firebaseapp.com/">RxJS</a></li><li><a href="http://reactivex.io/">ReactiveX</a></li><li><a href="https://coursetro.com/posts/code/150/RxJS-Operators-Tutorial---Learn-How-to-Transform-Observables">RxJS Operators Tutorial - Learn How to Transform Observables</a></li><li><a href="http://reactivex.io/rxjs/class/es6/MiscJSDoc.js~ObserverDoc.html">Observer | RxJS API Document</a></li></ul><ul><li><strong>The introduction to Reactive Programming you’ve been missing: </strong><a href="https://gist.github.com/staltz/868e7e9bc2a7b8c1f754">https://gist.github.com/staltz/868e7e9bc2a7b8c1f754</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b05e186c115" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thecodinghype/reactive-programming-in-javascript-using-rxjs-3b05e186c115">Reactive Programming in Javascript using RxJS</a> was originally published in <a href="https://medium.com/thecodinghype">The Coding Hype</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Welcome!]]></title>
            <link>https://medium.com/thecodinghype/welcome-b009f08e4059?source=rss----9fceaf0f32f4---4</link>
            <guid isPermaLink="false">https://medium.com/p/b009f08e4059</guid>
            <category><![CDATA[first]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[welcome]]></category>
            <dc:creator><![CDATA[László Harri Németh]]></dc:creator>
            <pubDate>Mon, 10 Dec 2018 09:01:01 GMT</pubDate>
            <atom:updated>2019-02-28T14:41:58.942Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2t-I46tM4yRXT1zR" /><figcaption>Photo by <a href="https://unsplash.com/@dsmacinnes?utm_source=medium&amp;utm_medium=referral">Danielle MacInnes</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Welcome to <a href="https://medium.com/thecodinghype">The Coding Hype</a>! My name is Harri, and I plan publishing articles about various programming languages and technologies. Some of these articles will be about features of a specific software library, others will be more like a tutorial, where I build a complete app. I hope you will find these articles useful.</p><p>Thank you for reading this welcome message.</p><p>Harri</p><p><strong>LinkedIn</strong>: <a href="https://www.linkedin.com/in/nlharri/">https://www.linkedin.com/in/nlharri/</a></p><ul><li><a href="http://nlharri.hu/">László Harri Németh (nlharri)</a></li><li><a href="https://nlharri.github.io/">László Harri Németh</a></li><li><a href="https://github.com/nlharri">nlharri - Overview</a></li><li><a href="https://twitter.com/CodingHype">The Coding Hype (@CodingHype) | Twitter</a></li><li><a href="https://twitter.com/HarriLaszlo/">László Harri Németh (@HarriLaszlo) | Twitter</a></li><li><a href="https://nlharri.github.io/thecodinghype/">{thecodinghype}</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b009f08e4059" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thecodinghype/welcome-b009f08e4059">Welcome!</a> was originally published in <a href="https://medium.com/thecodinghype">The Coding Hype</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>