<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Paschal on Medium]]></title>
        <description><![CDATA[Stories by Paschal on Medium]]></description>
        <link>https://medium.com/@_Obbap?source=rss-dba5ed7f7576------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*O4Nlu281J8lAmLVjEKvqVw.jpeg</url>
            <title>Stories by Paschal on Medium</title>
            <link>https://medium.com/@_Obbap?source=rss-dba5ed7f7576------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 03:11:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@_Obbap/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Hello world in Go from Rust]]></title>
            <link>https://medium.com/@_Obbap/hello-world-in-go-from-rust-a8064f62f9c1?source=rss-dba5ed7f7576------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8064f62f9c1</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Paschal]]></dc:creator>
            <pubDate>Sun, 07 Jan 2024 20:30:56 GMT</pubDate>
            <atom:updated>2024-01-07T20:30:56.093Z</atom:updated>
            <content:encoded><![CDATA[<p>Suppose every software in the world was written in just one programming language Eg. C. In that case, there’ll be no need for bindings and foreign function interfaces but since we have thousands of programming languages, genuine use cases arise where communicating across programming languages is necessary.</p><ul><li>Some programming languages are more performant than others and you’ll need to hand off computation-intensive tasks to these languages.</li><li>Some programming languages are state of the art in different areas, Eg, Javascript with Browsers, Python with Data, and C with Embedded systems, so it’ll be easier to utilize the existing libraries instead of reinventing the wheel.</li><li>Some languages are strict and strongly typed; you want to prototype fast but not compromise on performance. An example is Game development or NGINX module extensions with Lua and C.</li></ul><h3>The Base C Layer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*G2-jjFQ0bzgvVSDTAOTFvg.png" /></figure><p>Golang uses cgo to communicate with external C libraries and Rust uses FFI (Foreign function interfaces) to export C functions. Additionally, a library for automatically generating bindings can be used to generate the header files (.h). In our case, we’ll only be exporting two C functions, so using <a href="https://github.com/mozilla/cbindgen">cbindgen</a> is overkill but we’ll use it regardless because why not?</p><p>Firstly, we’ll write the rust functions we want to export. We’ll start by creating a new rust library:</p><pre>cargo new r --lib</pre><p>This means we’re creating a new rust library called r.</p><p>In our Cargo.toml, we’ll specify that this crate is a dynamic library and then include the libc and cbindgen dependencies.</p><pre>[package]<br>name = &quot;r&quot;<br>version = &quot;0.1.0&quot;<br>edition = &quot;2021&quot;<br><br>[lib]<br>crate-type = [&quot;cdylib&quot;]<br><br>[dependencies]<br>libc = &quot;0.2.151&quot;<br><br>[build-dependencies]<br>cbindgen = &quot;0.26.0&quot;</pre><p>We’ll need libc to access some C types, specifically the c_char type. This is because strings are UTF-32 encoded (4 bytes) in C while they’re UTF-8 encoded in Rust, meaning they can have variable sizes (1 to 4 bytes).</p><h3>Rust Functions</h3><p>To write our hello_worldfunction which will be called from Go, we’ll need the no_mangle annotation so the linker can find the function while linking without the Rust compiler <a href="https://rust-lang.github.io/rfcs/2603-rust-symbol-name-mangling-v0.html">mangling</a> it.</p><p>Then we can write our functions hello_world and hello_world_free :</p><pre>extern crate libc;<br><br>use std::ffi::CString;<br><br>use libc::c_char;<br><br>#[no_mangle]<br>pub extern &quot;C&quot; fn hello_world(item: *mut c_char) -&gt; *mut c_char {<br>    unsafe {<br>        let c_str =<br>            CString::new(format!(&quot;hello world {:?}&quot;, CString::from_raw(item))).expect(&quot;dont fail&quot;);<br>        c_str.into_raw()<br>    }<br>}<br><br>#[no_mangle]<br>pub extern &quot;C&quot; fn hello_world_free(item: *mut c_char) {<br>    unsafe {<br>        if item.is_null() {<br>            return;<br>        }<br>        let _ = CString::from_raw(item);<br>    };<br>}</pre><p>hello_world accepts a mutable pointer to a char array as an argument and returns the same. The unsafe keyword is needed as the rust compiler can’t guarantee that from_raw which entails dereferencing a null pointer, won’t lead to undefined behavior. Finally, we use into_raw to hand ownership back to the caller, in this case, Go.</p><p>hello_world_free accepts a mutable pointer, and calls from_raw on it, so we can properly reconstruct it, claim ownership, and then drop it. This is to avoid memory leaks.</p><pre>cbindgen::Builder::new()<br>        .with_crate(crate_dir)<br>        .with_config(config)<br>        .generate()<br>        .expect(&quot;Unable to generate bindings&quot;)<br>        .write_to_file(&quot;bindings.h&quot;);</pre><p>To generate the bindings, we’ll add a build script build.rs which uses cbindgen to generate the bindings.h file. Then we can run:</p><pre>cargo build</pre><p>If everything goes smoothly, we should have a compiled binary and a newly created bindings.h file with the following methods in it:</p><pre>char *hello_world(char *item);<br><br>void hello_world_free(char *item);</pre><h3>Go</h3><p>After building the Rust binary, we’ll need to tell the linker where to find it and we can do this by passing the linker flags via cgo. We’ll also need to include (think import) the bindings.h file so we can call the rust methods.</p><pre>// #cgo LDFLAGS: -L/Users/pbaba/projects/go-rust/r/target/debug -lr<br>// #include &lt;bindings.h&gt;<br>import &quot;C&quot;                   </pre><p>Finally, we can use the hello_world function and include the &quot;merry christmas&quot; string as an argument. We’ll also defer the hello_world_free method call, which will free the memory referenced by the pointer b afterward.</p><pre> a := C.CString(&quot;merry christmas&quot;)<br> b := C.hello_world(a)<br> defer C.hello_world_free(b)<br> fmt.Println(C.GoString(b))</pre><p>Then we can run go run main.go and it&#39;s alive:</p><pre>hello world. &quot;merry christmas&quot;</pre><p>In some cases, we can do without the hello_world_free function and replace it with the custom free function provided by cgo</p><pre>defer C.free(unsafe.Pointer(b))</pre><p>This should replace the function we already have so we don’t end up freeing the same location in memory twice and causing a double free:</p><pre>malloc: Double free of object 0x7f8c340040a0</pre><p>But for CStrings, <a href="https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#416-419">The Rust documentation</a> recommends we free this explicitly by reconstructing and then dropping it instead of using C’s free.</p><p>The rest of the code is <a href="https://github.com/obbap1/go-rust">on GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8064f62f9c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Failure Detection: The Phi Accrual Failure Detector]]></title>
            <link>https://medium.com/@_Obbap/failure-detection-the-phi-accrual-failure-detector-d6abe972d106?source=rss-dba5ed7f7576------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6abe972d106</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Paschal]]></dc:creator>
            <pubDate>Thu, 21 Oct 2021 09:32:21 GMT</pubDate>
            <atom:updated>2021-10-21T09:32:21.694Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*03BgBsTlJLL8l5e1P7K3Tg.png" /></figure><h3><strong>Introduction</strong></h3><p>In distributed systems, Nodes need to know if their peers are still healthy and update their peer lists accordingly. The simplest way to do this is with heartbeats. If there is a network with nodes A, B, and C, A sends heartbeat messages to its peers B and C saying “I’m still here”. If B and Cdon&#39;t hear from node Aafter a particular period, they can assume that node Ais dead and can no longer handle requests, and nodes B and Cwill stop sending traffic to node A.</p><p>The question is how long should nodes B and Cwait for A before marking it as dead. Twenty seconds ?, Thirty seconds ?. If a very short time is chosen as the threshold, there will be lots of false positives on the “dead nodes” peer list. A lot of nodes will be marked as dead when they are actually not. They might have had bad internet connections etc. On the other hand, if a longer time is chosen as the threshold, there will be lots of failed requests because dead nodes will keep getting traffic as though they’re still active and dropping them. So what exactly is the sweet spot? The Phi Accrual failure detector.</p><h3>The Phi Accrual Failure Detector</h3><p>The Phi Accrual failure detector, which was originally introduced in this <a href="https://www.semanticscholar.org/paper/Performance-Evaluation-of-the-.-Accrual-Failure-Hayashibara-Takizawa/5795d75e91429342ea4546c8bd4bbf7da713da61?p2df">paper</a> uses a suspicion model. For example, when nodes B and Cstartup, they’ll set the confidence level they have in node A to 0.5, where the scale is from 0 to 1. After a particular period, if node A doesn&#39;t respond, the confidence level is dropped by 0.1 , which makes the new confidence 0.4. If it does respond, it is increased by 0.1 and the confidence is 0.6. A threshold can then be set, that if node A doesn&#39;t respond when it&#39;s down to 0.2 then we can mark the node as dead. This is a more compound approach because it recognizes the past response times of the node. Data can also be stored, and used to analyze and decide what to set the threshold for a node to be marked as dead to.</p><h3>Simulation</h3><p>I did a small simulation with Docker and Golang, and this is what it looked like.</p><h4>Leader</h4><p>The first component is the Leader. I set up the entity in <a href="https://github.com/obbap1/phi-accural-detector/blob/master/leader/leader.go">leader.go</a>. The Leader receives the heartbeats, updates the tables, manages the <a href="https://github.com/obbap1/phi-accural-detector/blob/master/leader/leader.go#L37">thresholds</a> and the <a href="https://github.com/obbap1/phi-accural-detector/blob/master/leader/leader.go#L39">failure points</a>.</p><pre>var (</pre><pre>   threshold = 15</pre><pre>   failurePoint = 0.2</pre><pre>)</pre><p>The threshold is set to 15 and is denominated to seconds . This means if we don&#39;t hear from a node after fifteen seconds, the confidence level will be decremented by 0.1.</p><p>The failurePoint is set to 0.2 and once the node’s confidence level reaches the failurePoint or lower, it will be marked as dead.</p><h4>Follower</h4><p>The next entity is the Followerwhich is setup in the <a href="https://github.com/obbap1/phi-accural-detector/blob/master/follower/follower.go">follower.go</a> file. The followers will send periodic <a href="https://github.com/obbap1/phi-accural-detector/blob/master/follower/follower.go#L14">heartbeats</a> to the leader. A heartbeat looks like this:</p><pre>type HeartBeat struct {</pre><pre>   IpAddress string</pre><pre>   Pid       int</pre><pre>   Timestamp int64</pre><pre>}</pre><p>The follower sends its IP address, process id (PID), and timestamp to the leader periodically.</p><p>I setup two docker containers, phi_leader to hold the leader executable and phi_follower for the follower executable.</p><p>I scaled the phi_follower instance to 5 instances on a docker swarm network.</p><pre># docker service scale phi_follower=5  <br>                    <br>phi_follower scaled to 5<br>overall progress: 0 out of 5 tasks <br>1/5: ready     [======================================&gt;            ] <br>2/5: ready     [======================================&gt;            ] <br>3/5: starting  [============================================&gt;      ] <br>4/5: preparing [=================================&gt;                 ] <br>5/5: ready     [======================================&gt;            ]</pre><p>After running this process for about five minutes, I tailed the leader’s logs and the peer list looks like this:</p><pre># docker service logs phi_leader -f</pre><pre>Received heart beat from process with IP 10.0.4.222 and PID 1<br>updating Accural failure detection table...<br>    *------------*-----*-----------------*------------*<br>    ╪     IP     ╪ PID ╪   CONFIDENCE    ╪    TIME    ╪<br>    *------------*-----*-----------------*------------*<br>    ╪ 10.0.4.219 ╪   1 ╪        0.500000 ╪ 1634756932 ╪<br>    ╪ 10.0.4.223 ╪   1 ╪        0.500000 ╪ 1634756940 ╪<br>    ╪ 10.0.4.222 ╪   1 ╪        0.600000 ╪ 1634756942 ╪<br>    ╪ 10.0.4.224 ╪   1 ╪        0.600000 ╪ 1634756924 ╪<br>    ╪ 10.0.4.225 ╪   1 ╪        0.900000 ╪ 1634756922 ╪<br>    *------------*-----*-----------------*------------*<br>    ╪                    TOTAL PROCESSES ╪     5      ╪<br>    *------------*-----*-----------------*------------*<br>    </pre><p>The five different nodes have been registered on the leader, with different confidence levels and timestamps. With the confidence levels, all the peers are healthy.</p><p>Now I stopped two nodes, and watched to see if the detector decrements their confidence levels.</p><pre>// Stop first container<br># docker stop 14d07e02a1ad            <br>14d07e02a1ad</pre><pre>// Stop second container<br># docker stop 3829bb23fe41<br>3829bb23fe41</pre><p>After 17 seconds, which is below the threshold of 15 seconds, a node hadn’t sent a heartbeat and the confidence level was decreased. Node with IP 10.0.4.223 has been dropped to 0.9</p><pre># docker service logs phi_leader -f</pre><pre>Checking for inactive processes...<br>Haven&#39;t received a heartbeat from process with ip 10.0.4.223 and pid 1 for the past 17 seconds<br>Decrementing process confidence by 0.1<br>    *------------*-----*-----------------*------------*<br>    ╪     IP     ╪ PID ╪   CONFIDENCE    ╪    TIME    ╪<br>    *------------*-----*-----------------*------------*<br>    ╪ 10.0.4.219 ╪   1 ╪        1.000000 ╪ 1634757451 ╪<br>    ╪ 10.0.4.223 ╪   1 ╪        0.900000 ╪ 1634757439 ╪<br>    ╪ 10.0.4.222 ╪   1 ╪        1.000000 ╪ 1634757453 ╪<br>    ╪ 10.0.4.224 ╪   1 ╪        1.000000 ╪ 1634757440 ╪<br>    ╪ 10.0.4.225 ╪   1 ╪        1.000000 ╪ 1634757430 ╪<br>    *------------*-----*-----------------*------------*<br>    ╪                    TOTAL PROCESSES ╪     5      ╪<br>    *------------*-----*-----------------*------------*</pre><p>After a few minutes of tailing the logs, one of the nodes go below the failure point of 0.2and is marked as dead. The leader removes this node from its peer list, and the total drops to 4</p><pre># docker service logs phi_leader -f</pre><pre>This process with ip 10.0.4.224 and pid 1 now has confidence 0.200000 which is below or equal to the failure point 0.200000 and will be marked as dead<br>    *------------*-----*-----------------*------------*<br>    ╪     IP     ╪ PID ╪   CONFIDENCE    ╪    TIME    ╪<br>    *------------*-----*-----------------*------------*<br>    ╪ 10.0.4.219 ╪   1 ╪        0.900000 ╪ 1634757996 ╪<br>    ╪ 10.0.4.223 ╪   1 ╪        1.000000 ╪ 1634757998 ╪<br>    ╪ 10.0.4.222 ╪   1 ╪        1.000000 ╪ 1634758005 ╪<br>    ╪ 10.0.4.227 ╪   1 ╪        0.700000 ╪ 1634758010 ╪<br>    *------------*-----*-----------------*------------*<br>    ╪                    TOTAL PROCESSES ╪     4      ╪<br>    *------------*-----*-----------------*------------*</pre><p>So it worked! The code to the full implementation and simulation of the Phi Accrual Detector can be found <a href="https://github.com/obbap1/phi-accural-detector">here</a>.</p><p>Thank you for reading!</p><h3>Notes</h3><ol><li>The actual phi accrual detector is more complex than this, it uses a better probabilistic model like calculating the mean and standard deviation of previous results to determine the threshold and failure point instead of hardcoding the values as we did. You can find a good read <a href="https://doc.akka.io/docs/akka/current/typed/failure-detector.html">here</a> (phi = -log10(1 - F(timeSinceLastHeartbeat)) )</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6abe972d106" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build a simple social media monitor with NodeJS, GraphQL, and Vue]]></title>
            <link>https://medium.com/free-code-camp/how-to-build-a-simple-social-media-monitor-with-nodejs-graphql-and-vue-55ffe4124ab5?source=rss-dba5ed7f7576------2</link>
            <guid isPermaLink="false">https://medium.com/p/55ffe4124ab5</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Paschal]]></dc:creator>
            <pubDate>Thu, 31 Jan 2019 19:55:06 GMT</pubDate>
            <atom:updated>2019-02-02T17:01:13.940Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*apsmd1svbRnvOh_Evak5nA.png" /><figcaption>Thanks to <a href="https://undraw.co/illustrations">undraw!</a></figcaption></figure><h4>Introduction</h4><p>We’ll build a simple monitor that will track the number of people that followed us on specific dates, using Medium as the use case. This is just a bare prototype and can be done for any other social media or networking platform.</p><p>In the end, we should have something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IWAiDTjoSP9FrikYuvcvvA.png" /></figure><p>To achieve this, we will use the<em> </em><a href="https://github.com/mscdex/node-imap"><em>node-imap</em></a><em> </em>package. The two major protocols for handling emails are IMAP (Internet Messaged Access Protocol) and POP (Post office protocol). IMAP is preferred, because it always syncs with the mail server, hence the changes made on the mail client will appear immediately on the webmail inbox.</p><h4>Prerequisites</h4><ul><li>NodeJS</li><li>VueJS</li><li>A Gmail account</li></ul><h4>Setup the back-end with node-imap and apollo</h4><p>Firstly, install the necessary packages.</p><pre>npm i --save node-imap apollo-server mailparser</pre><p>Now you can define the types and resolver and then run the apollo server.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4aa8409be3d4a6b1eda1c472a38490cd/href">https://medium.com/media/4aa8409be3d4a6b1eda1c472a38490cd/href</a></iframe><p>A ‘<strong>User</strong>’ type that has the email and password string types as its schema has been defined, and a mutation called<strong> ‘imapMutation’ </strong>which receives the email and password from the user and then returns a response with the User type.</p><p>The resolver handles the mutation, and then you can work with the arguments sent from the client.</p><p>Now you can run the server.</p><p>You can then import the <strong>node-imap</strong> and <strong>mailparser </strong>modules. The <strong>mailparser</strong> module will be used to receive the mail responses as JSON.</p><pre>const Imap = require(&#39;imap&#39;)<br>const simpleParser = require(&#39;mailparser&#39;).simpleParser</pre><p>You are going to create a ‘<strong>connectImap’</strong> function that will handle our IMAP functionality. From the <a href="https://github.com/mscdex/node-imap">node-imap</a> documentation, you can get the skeleton of how the module works, and then copy and paste it into the code. It basically works with callbacks and emitters, so we’ll wrap it in a promise.</p><p>You should have something like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c623756d8355502d0d8cd52dfca0c4dc/href">https://medium.com/media/c623756d8355502d0d8cd52dfca0c4dc/href</a></iframe><p>When the ‘<strong>ready</strong>’ event is called, we connect to our mail, and then we can search for messages. So, we’ll search for emails from the medium account that handles followers (<strong><em>noreply@medium.com</em></strong>).</p><p>Our ‘<strong><em>ready</em></strong>’ event should look like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f48ff87c25d2a68bf4dcc10976061106/href">https://medium.com/media/f48ff87c25d2a68bf4dcc10976061106/href</a></iframe><p>We search for emails where each subject contains a ‘<strong><em>started following you</em></strong>’ substring. Then, we split the arrays with either a comma or the conjunction ‘and’ to get the number of followers, and then handle cases like ‘<strong><em>Peter and 3 others started following you</em></strong>’. After splitting the string above, we will have an output:</p><pre>[<br>  &#39;Peter&#39;,<br>  &#39;3 others started following you&#39;<br>]</pre><p>The length of this array is <strong>2</strong>, so we have two followers. If the subject contains ‘<strong><em>others</em></strong>’, we take the digit behind it and add to the length of the array, which is <strong>5</strong> and then we subtract <strong>1</strong> to get rid of the ‘<strong><em>3 others started following you</em></strong>’ string. This leaves us with <strong>4</strong>.</p><p>Then, we resolve the promise when the ‘<strong><em>end</em></strong>’ event is fired (<em>imap.once(‘end’)</em>).</p><p>Since we will have to send the array to our apollo client, we will need to define the type of the ‘<strong><em>graphPoints</em></strong>’ array.</p><p>Our type definitions should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8e0a44f8dfcacb34730d020f492d627/href">https://medium.com/media/f8e0a44f8dfcacb34730d020f492d627/href</a></iframe><p>We added the <strong>data</strong> key to the ‘<strong><em>User</em></strong>’ type, which will hold the ‘<strong><em>graphPoints</em></strong>’ value, and its type is an array of objects with the ‘<strong><em>Graph</em></strong>’ type.</p><p>Finally, we handle the resolver, which will get the email and the password of the user and then return the <strong>email</strong> and the data (<strong><em>graphPoints</em></strong>).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d90a2f9c341c25468b5d8fee52e9312d/href">https://medium.com/media/d90a2f9c341c25468b5d8fee52e9312d/href</a></iframe><p>If we log the <strong>user </strong>object, our structure should be something like this:</p><pre>email: String,<br>data: [ { numberOfFollowers: 1, date: 2017-07-05T07:53:18.000Z },<br>        { numberOfFollowers: 1, date: 2017-07-07T19:34:57.000Z }<br>      ]</pre><h4>Setup the front-end with v-charts and apollo client</h4><p>Now, we want to get the data sent from the server and plot the chart with the <a href="https://www.npmjs.com/package/v-charts">v-charts</a> module.</p><p>But first, we install our dependencies.</p><pre>npm install --save vue-chartjs vue-apollo apollo-client apollo-link-http apollo-cache-persist apollo-cache-inmemory graphql graphql-tag moment</pre><p>I know what you’re thinking — that’s a lot of dependencies. If you have troubles setting up a Vue project, you can find out how to do that <a href="https://cli.vuejs.org/guide/creating-a-project.html#vue-create">here</a>. We should also include <a href="https://vuetifyjs.com/en/getting-started/quick-start">vuetify</a> and the <a href="https://router.vuejs.org/installation.html#direct-download-cdn">vue-router</a> if we want to style the project and create additional routes.</p><p>In our ‘<strong><em>src</em></strong>’ folder, we can create a ‘<strong><em>config</em></strong>’ folder. The structure should look like this:</p><pre>|src<br>  |config<br>     -graphql.js<br>     -index.js<br>     -LineChart.js<br>  |pages<br>      -login.vue<br>  |router<br>      -index.js<br>  App.vue<br>  main.js</pre><p>We will have to set up our graphql client in the <strong><em>src/config/index.js</em></strong> file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0bb75b047424802e0302a255f491be2e/href">https://medium.com/media/0bb75b047424802e0302a255f491be2e/href</a></iframe><p>Make sure the <strong><em>uri</em></strong> is on the same port as your apollo server, by default the apollo server runs on port <strong>4000</strong>. Our apollo client is then set up with the <em>httpLink</em> and the <em>cache</em>.</p><p>The <strong><em>src/config/graphql.js</em></strong> file should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5a7e639259961e358371ed6e25828d2/href">https://medium.com/media/e5a7e639259961e358371ed6e25828d2/href</a></iframe><p>This query will submit the <strong>email</strong> and the <strong>password</strong> of the user to the imapMutation and then get the <strong>email</strong> and the <strong>data</strong>(graphPoints) from the apollo server.</p><p>Then, we create our chart component in the <strong><em>src/config/LineChart.js</em></strong> file. We can use charts ranging from bar charts to histograms. A line chart was used in this example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/602963b602801b2b9d709d36473ec412/href">https://medium.com/media/602963b602801b2b9d709d36473ec412/href</a></iframe><p>We can import the ‘<strong><em>vue-apollo</em></strong>’ package in our main.js file and include the <strong>apolloProvider</strong> when initializing the app.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/faeebf90ff744010b60aa9b05ccde66a/href">https://medium.com/media/faeebf90ff744010b60aa9b05ccde66a/href</a></iframe><p>Finally, we will set up the <strong>src/pages/login.vue</strong> file, which we should have configured as the component for the default home route ‘/’ in the <strong>src/router/index.js</strong> file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12107af09026b95490eb0c26a819b2dd/href">https://medium.com/media/12107af09026b95490eb0c26a819b2dd/href</a></iframe><p>So we created a basic form that accepts the email and password of the user and then send this data to the server through the <strong><em>signup()</em></strong> method. The <strong><em>plotGraph()</em></strong> method loops through the response(graphPoints) and pushes the dates to the labels array and the number of followers to the data array.</p><p>After styling using the ‘<strong><em>options</em></strong>’ object, we should have something like the screenshot shown during the introduction to this project.</p><h4>Conclusion</h4><p>You can still do more with your personal project, but the aim of this was to show how to work with the node-imap package, and how apollo works as a server and as a client. If you had any problems with this project, you can leave a comment or send a message on <a href="https://twitter.com/_Obbap">Twitter</a>.</p><p>You can try the live version of <a href="https://medium-followers.netlify.com/">this</a>, or you could check out the repositories for the <a href="https://github.com/obbap1/MonitorFollowers_frontend">client</a> and <a href="https://github.com/obbap1/MonitorFollowers_backend">server</a> applications on GitHub.</p><p>If you want to learn new technologies and frameworks, you can do so <a href="https://www.microverse.org/">here</a> and if you learned anything at all, please do well to clap below.</p><p><em>I will like to thank </em><a href="https://medium.com/u/f842674fe29"><em>Wes Wagner</em></a><em> for his feedback in making this article.</em></p><p>Thanks!</p><figure><a href="http://www.microverse.org/"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SRAIx1jmXTBHByfDCOtZig.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55ffe4124ab5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/how-to-build-a-simple-social-media-monitor-with-nodejs-graphql-and-vue-55ffe4124ab5">How to build a simple social media monitor with NodeJS, GraphQL, and Vue</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I built a Telegram Reminder bot with Node JS, the IBM Watson API and Firebase]]></title>
            <link>https://medium.com/hackernoon/how-i-built-a-telegram-reminder-bot-with-node-js-the-ibm-watson-api-and-firebase-7128c778e3d7?source=rss-dba5ed7f7576------2</link>
            <guid isPermaLink="false">https://medium.com/p/7128c778e3d7</guid>
            <category><![CDATA[telegram]]></category>
            <category><![CDATA[telegram-reminder-bot]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[bots]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Paschal]]></dc:creator>
            <pubDate>Tue, 18 Dec 2018 01:34:10 GMT</pubDate>
            <atom:updated>2018-12-18T01:34:10.771Z</atom:updated>
            <content:encoded><![CDATA[<h3>How I built a Telegram Reminder Bot with Node JS, the IBM Watson API and Firebase</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h89l_KJR8w2NrzQXtPCAmw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/R4WCbazrD1g?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Rock’n Roll Monkey</a> on <a href="https://unsplash.com/search/photos/bot?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><strong>Table of Contents</strong></p><ol><li>Introduction</li><li>Prerequisites</li><li>Create the bot with Node JS</li><li>Connecting the bot to a real time DB(Firebase)</li><li>Run the Cron Job</li><li>Script to connect to the IBM Watson API</li><li>Deploy to Glitch</li><li>Conclusion</li></ol><h3>Introduction</h3><p>This Telegram bot, would simply take three commands.</p><ul><li>/start — Initializes our bot.</li><li>/save — Saves the string we will like to be reminded of later.</li><li>/time — Saves the time we would love to carry out this task.</li></ul><p>Then, this data is saved to firebase, and a cron job is initialized, which will run at the set time. This cron job, sends a text reminder to the user, and is then converted to an audio file, using the Text to Speech IBM Watson API, and is also sent to the user.</p><h3>Prerequisites</h3><ul><li>A Telegram bot, This bot can be created by sending a ‘/start’ message to the <a href="https://web.telegram.org/#/im?p=@BotFather">Bot Father</a> account on Telegram. The bot token should also be gotten.</li><li>An <a href="https://idaas.iam.ibm.com/">IBM watson</a> account (it’s free).</li><li>A real-time database,<a href="https://firebase.google.com/"> firebase / firestore</a>.</li><li>A <a href="https://glitch.com/">Glitch account</a>, which just needs your Github account.</li><li>A little bit of regex and bash(Nothing to be worried about).</li></ul><h3>Create a bot with Node JS</h3><p>Ok, to begin, we will need to install the modules we will need. So from our directory, we will run this in the terminal:</p><pre>$ mkdir telegramBot &amp;&amp; cd telegramBot<br>$ npm init<br>$ npm install node-telegram-bot-api node-cron firebase-admin shelljs</pre><p>We will be using the <strong>node-telegram-bot-api </strong>as a wrapper. To begin, we will create an <strong>index.js</strong> file in our directory. We will add the following lines to our index.js file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54b1396f5388e99e663c28014a203520/href">https://medium.com/media/54b1396f5388e99e663c28014a203520/href</a></iframe><p>So we initialize the bot with the token gotten from the Bot Father account. The polling option on line 6, keeps the channel between the bot and the user alive. Its a web socket thing. We also declare a reminder variable, which holds what we want to be reminded of.</p><h3>/start</h3><p>Then, we will have our server listen to when the ‘/start’ command is inputted by our user. So we will add an <strong>onText </strong>listener, to the index.js file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93f3fdbc3aa45c64b95c493f09fb1633/href">https://medium.com/media/93f3fdbc3aa45c64b95c493f09fb1633/href</a></iframe><p>This listens to when the ‘/start’ command is passed, and then responds with a callback that contains a ‘msg’ object which holds the chat id, the name of the user etc.</p><p>When this condition is met, the bot sends a message to the chat id, asking what the user, what he wants to be reminded of. So we are done with the first command!</p><h3>/save</h3><p>This command will save what we want to be reminded of. This listener will be triggered after the ‘/start’ command is passed. So we will pass this function, in the promise returned(.then)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db64da968513a03ed316ba17ef2367ed/href">https://medium.com/media/db64da968513a03ed316ba17ef2367ed/href</a></iframe><p>So we listen to when the ‘./save’ is entered, and then the ‘match’ variable in the callback returns an array with what is matched.</p><p>If the user enters <strong><em>/save ‘wash my clothes’</em></strong>, then the ‘wash my clothes’ string will have the first index in the array i.e [‘/save wash my clothes’, ‘wash my clothes’]. When this is gotten and saved, we then send a message asking for the time. We are done with the second command!</p><h3>/time</h3><p>Now, we will save the time. This should be entered in the promise chain of the save command. We want to save the command with the format, <strong>HH:MM:SS:(AM OR PM)</strong>. So our time function should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/271d15f4612ccef02f59eddfdbeab343/href">https://medium.com/media/271d15f4612ccef02f59eddfdbeab343/href</a></iframe><p>So the regex, matches the format, and then we get the time by splitting the match response. The match variable looks like this:</p><pre>[ &#39;/time 06:33:33:PM&#39;,<br>  &#39;06&#39;,<br>  &#39;33:33&#39;,<br>  &#39;PM&#39;,<br>  index: 0,<br>  input: &#39;/time 06:33:33:PM&#39; ]</pre><p>So splitting the first item in the array, we get <strong>06:33:33:PM</strong>, and then we send a thanks message. But our bot doesn’t actually save the users request yet, and it surely doesn’t remind the user. So we need to fix this.</p><p>At this stage, our index.js file should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a508a48cb1f109e446ebe6e36f76a64/href">https://medium.com/media/8a508a48cb1f109e446ebe6e36f76a64/href</a></iframe><p>Our interaction with our bot, should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*t3gr-2LSy6gjJ_VwWHZFrA.png" /></figure><h3>Connecting the bot to a real time DB(Firebase)</h3><p>Now, we will create a <strong>database.js </strong>file in the root of our directory, which will handle our connection to the firestore db. Our database.js file should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/686319f8d84b7677e7b9cc72b7d6d7fa/href">https://medium.com/media/686319f8d84b7677e7b9cc72b7d6d7fa/href</a></iframe><p>Now, we can import our database.js file at the top of our index.js file.</p><pre>const db = require(&#39;./database&#39;).database;</pre><p>We also want to save the user’s request with the user’s chat name, but if the user makes more than one request, it will be a duplicate. So we can attach a random string to each document to be stored on firestore. To do this, we’re going to create a <strong>helper.js </strong>file in our root, and it would look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea1134383e1180109ce7107a90e593bd/href">https://medium.com/media/ea1134383e1180109ce7107a90e593bd/href</a></iframe><p>This returns a string with whatever length we pass. We can also import this file at the top of our index.js file.</p><pre>const generator = require(&#39;./helper&#39;);</pre><p>Now, we will go back to the function that handles our <strong><em>/time</em></strong> command, before sending the ‘Thank you’ reply, and then we add this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e26e35d7b86ed8348bcfdd4952589bd/href">https://medium.com/media/4e26e35d7b86ed8348bcfdd4952589bd/href</a></iframe><p>Initially, i created a collection on my db called ‘reminder’. And then i pass the payload using the <strong><em>.set</em></strong> command to that collection. Now, there is a <strong>hasUserBeenReminded </strong>key, which helps us keep track of if the user has been reminded of a certain task.</p><p>If we interact with our bot again, after running the <strong><em>/time</em></strong> command, our db should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*MmqNgTHj3m4l4yaEE9l2Jg.png" /><figcaption>firestore db</figcaption></figure><p>If this works fine, we can then run a cron job, to remind the user at the set time. We can add the dependency at the top of the index.js file.</p><h3>Run the Cron Job</h3><pre>const cron = require(&quot;node-cron&quot;);</pre><p>Then, we can continue with the function that listens to our <strong><em>/time</em></strong> command.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0980969784d41308624f66eb449bd826/href">https://medium.com/media/0980969784d41308624f66eb449bd826/href</a></iframe><p>So we basically get the hour and the minute the user wants to be reminded of a certain task, and then schedule it with the cron dependency. Normally, the cron scheduler has a pattern:</p><pre><strong>* * * * * *</strong></pre><p>These asterisks represent the second(optional), minute,hour,day,month and year respectively. So we ignored the second option, and chose the hour and minute. When it’s time, the event is triggered, and the reminder is sent, the <strong>hasUserBeenReminded </strong>key is also set to true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*mhYOHFBPCYB_a16RD0pM-Q.png" /><figcaption>We should have a message like this, when the time comes.</figcaption></figure><h3>Script to connect to the IBM Watson API</h3><p>We also want the bot to send a voice note of our reminder. Something like a <strong><em>‘wash your clothes’ </em></strong>will do. To do this, we will use the text to speech service on the IBM Watson API. This will convert the file to an audio file of the format we want(Telegram accepts the <strong>.ogg</strong> format)<strong> </strong>and then upload it.</p><p>To do this, we will be writing a simple shell script. We will name the file, textToAudio.sh, and it should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8056c3bbb98683da5e291c55b4a8c1f/href">https://medium.com/media/d8056c3bbb98683da5e291c55b4a8c1f/href</a></iframe><p>The ‘$1’ gets the first argument when the command is run. That will be our text. And then if that argument is not empty, do a post request with curl, else display a string <strong><em>‘No arguments’</em></strong>. If this runs successfully, the output <strong><em>remindersss.ogg</em></strong> will be added to the root directory.</p><p>We can run this in the terminal with the sh command, but to run this in node, we will need to add a dependency at the top of our index.js file.</p><pre>const shell = require(&#39;shelljs&#39;)</pre><p>So now, we will run this with the <strong><em>shell.exec</em></strong> command, and then the first argument will be what we want to be reminded of.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d330684e3227880f13b2d5c1102f1174/href">https://medium.com/media/d330684e3227880f13b2d5c1102f1174/href</a></iframe><p>This will execute the shell script, and then pass the reminder as the first argument. Then we send the audio to the user!</p><p>Our Interaction with the telegram bot should look like this now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*VKd2nLnk6V-jIAjbfZVmaA.png" /><figcaption>Audio file sent</figcaption></figure><h3>Deploy to Glitch</h3><p>Ok,this is really just plug and play. After creating a project on glitch, just copy and paste your code there, and you’re good to go.</p><h3>Conclusion</h3><p>This project still has many rough edges, one of which is queuing, because it takes just one request at a time among others. If you need clarification, there is a <a href="https://github.com/obbap1/telegram_bot">repository</a> for it.</p><p><em>Thank you very much for reading,if you liked it, please clap. if you have any questions or you need further clarification, you can leave a comment or a mail(paschalobba@yahoo.com).</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7128c778e3d7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/how-i-built-a-telegram-reminder-bot-with-node-js-the-ibm-watson-api-and-firebase-7128c778e3d7">How I built a Telegram Reminder bot with Node JS, the IBM Watson API and Firebase</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Workaround the Node JS File System]]></title>
            <link>https://medium.com/hackernoon/workaround-the-node-js-file-system-a596408b1dcf?source=rss-dba5ed7f7576------2</link>
            <guid isPermaLink="false">https://medium.com/p/a596408b1dcf</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[node-js-file-system]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Paschal]]></dc:creator>
            <pubDate>Fri, 30 Nov 2018 01:36:00 GMT</pubDate>
            <atom:updated>2018-11-30T01:36:00.997Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JggJLMOPdaUrHEl0NM35HQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/o6GEPQXnqMY?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Mr Cup / Fabien Barral</a> on <a href="https://unsplash.com/search/photos/files?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Hello, fellow members of the night’s watch. We will be looking at one of Node’s core API’s, the File System. I know we’ve been concerned with code splitting, bundle splitting, preloading and the never ending woes of the Internet Explorer, but we will be learning how Node interacts with our files and directories. This helps us handle images or assets on our server, store them properly, read the content of other files, write to files,etc.</p><p>We will be building a basic CRUD application using the file system. I think we can get started.</p><p>Our little folder structure should look like this:</p><pre>Database-----(folder)<br>crud.js------(file)</pre><p>The ‘Database’ folder is going to contain a file, that will hold our Automobile business data. This data is going to comprise of the name of a car, and it’s price. It will be stored in JSON. Obviously, this cannot be done in production, and in order to ensure that no one thinks of it, i’m stating it unequivocally.</p><h3>CREATE</h3><p>Now, we will be creating our <strong><em>cars.json</em></strong> file, from our <strong><em>crud.js </em></strong>file. Firstly, we will need the file system module, and the path module.</p><pre>const fs = require(&#39;fs&#39;);<br>const path = require(&#39;path&#39;);</pre><p>Then, we will create the crud object and its base directory, which holds the path from the crud.js file to the database folder.</p><pre>const crud = {};<br>crud.baseDir = path.join(__dirname,&#39;./database&#39;);</pre><p>Now, we will add a create function, and our crud.js file should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/161b1031caba19a17091f72279ae7ca2/href">https://medium.com/media/161b1031caba19a17091f72279ae7ca2/href</a></iframe><p>The ‘create’ function, holds the name of the file we want to create, and the data we want to write to the file. So we open a new file in the path we defined in the base directory, and it takes whatever name we assign.</p><p>‘wx’ means we can <strong>w</strong>rite to<strong> </strong>the file, but the operation will fail if the file already exists. There are so many other <a href="http://www.tutorialsteacher.com/nodejs/nodejs-file-system">operations</a> we can attribute to the file.</p><p>If there are no errors, Node attributes an identifier or a file descriptor to the file. If this identifier is found, we can then write to the file.</p><p>We want our database to look like this:</p><pre>[<br>    {name: &#39;&#39;, price: &#39;&#39;},<br>    {name: &#39;&#39;, price: &#39;&#39;}<br>]</pre><p>This is the reason, we push the data to the <strong>jsonArray </strong>variable, before sending it to the file.</p><p>We can go to the bottom of our page, and run this:</p><pre>crud.create(&#39;cars&#39;,{&#39;name&#39;: &#39;innoson&#39;,&#39;price&#39;:&#39;$4000&#39;});</pre><pre>//Then Obviously(in your console)<br>node crud</pre><p>All things being equal, this should create a <strong>cars.json</strong> file with the array inside it.</p><h3>READ</h3><p>Now, we should be able to read the data from the file we just created. Our read function should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b038622e6a0003f18e639e2f4d7bacb/href">https://medium.com/media/8b038622e6a0003f18e639e2f4d7bacb/href</a></iframe><p>This function goes to the base directory, which is the <strong>database</strong> folder and then reads the data from the file we pass into the function. The encoding format is <a href="https://en.wikipedia.org/wiki/UTF-8">UTF-8</a>, and without errors, our data should get logged.</p><p>We can go to the bottom of our page and run this:</p><pre>crud.read(&#39;cars&#39;);</pre><h3>UPDATE</h3><p>Now, we can use <strong>fs.truncate()</strong> to change the content of the whole file, but we will use <strong>fs.appendFile()</strong> to append data to our file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa156a2e62efabc5a4118180fb92922d/href">https://medium.com/media/fa156a2e62efabc5a4118180fb92922d/href</a></iframe><p>If we go to the bottom of the page, and run the update function</p><pre>crud.update(&#39;cars&#39;,{name:&#39;Tesla&#39;,price:&#39;$10&#39;})</pre><p>We will have an output like this:</p><pre>[<br>   {name: &#39;innoson&#39;,price:&#39;#4000&#39;}<br>]<br>,<br>{name: &#39;Tesla&#39;,price:&#39;$10&#39;}</pre><p>which is not what we desire, we need the object to be in the array. To do this, i came up with a plan.</p><ul><li>We will read the current content of the <strong>cars.json</strong> file</li><li><strong>Then</strong>, we will append our updates</li><li><strong>Then</strong>, we will truncate the file and replace.</li></ul><p>With the emphasis on ‘<strong>Then</strong>’, we will need to use promises. We will make use of another Node API, util.</p><p>Go to the top of your crud.js file and include:</p><pre>const { promisify } = require(&quot;util&quot;);</pre><pre>const readFile = promisify(fs.readFile);</pre><p>So, the ‘readFile’ variable will return promises. Our new crud.update function should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80cc7fe0ff7b93981a30c11a8392f5b4/href">https://medium.com/media/80cc7fe0ff7b93981a30c11a8392f5b4/href</a></iframe><p>So, we can create a new JSON file in the database folder, and test our update function.</p><pre>crud.create(&#39;cars-updated&#39;,{name:&#39;mercedes&#39;,price:&#39;$400&#39;})</pre><pre>crud.update(&#39;cars-updated&#39;,{name:&#39;Toyota&#39;,price:&#39;$550&#39;})</pre><p>The cars-updated.json file should have the desired format.</p><h3>DELETE</h3><p>To delete a file, we use the fs.unlink method. So our crud.delete function should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0da9c30a5713c9d9302fce916a61d69/href">https://medium.com/media/c0da9c30a5713c9d9302fce916a61d69/href</a></iframe><p>So, we can delete the cars.json file, since its no longer needed.</p><pre>crud.delete(&#39;cars&#39;)</pre><p>You can see the crud.js file <a href="https://gist.github.com/obbap1/36654c084ee67ab63017ea4932d724d5.js">here</a></p><p><em>Thank you very much for reading,if you liked it, please clap. if you have any questions or you need further clarification, you can leave a comment or a mail(paschalobba@yahoo.com).</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a596408b1dcf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/workaround-the-node-js-file-system-a596408b1dcf">Workaround the Node JS File System</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Church Family War: The story of a witness]]></title>
            <link>https://medium.com/@_Obbap/the-church-family-war-the-story-of-a-witness-f8a460bb6e3e?source=rss-dba5ed7f7576------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8a460bb6e3e</guid>
            <category><![CDATA[children]]></category>
            <category><![CDATA[parenting]]></category>
            <category><![CDATA[comedy]]></category>
            <category><![CDATA[christianity]]></category>
            <category><![CDATA[nigeria]]></category>
            <dc:creator><![CDATA[Paschal]]></dc:creator>
            <pubDate>Sun, 28 Oct 2018 20:27:37 GMT</pubDate>
            <atom:updated>2018-10-28T20:27:37.353Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*6DIf7PuD2AL7MPD344nNXw.jpeg" /></figure><p>In Nigeria, Sundays are specially dedicated to Church. Once ‘daddy’ and ‘mummy’ are going to church that means everybody in the house(age,religion and financial status notwithstanding!) is going to Church. This kind of family is my definition of a “church family”.</p><p>As a single youth, you go to church alone, and then you find a convenient spot where you can either listen attentively to the pastor or sleep, but so help you God, a “church family” steps in and sits right in front of you. There is no hope of hearing the pastor not to talk of hearing God.</p><h3>THE TRIUMPHANT ENTRY</h3><p>The average church family is made up of six individuals. The Father, Mother, Three kids(worst case scenario: three boys) and then someone to help the Mother manage the house, most times a relative.</p><p>When they come into the church, the Father leads the crew, He is looking all pious and is quickly followed by his wife(They are wearing clothes made with the same ‘ankara’). She is carrying the youngest of the boys in her arms, he is so cute and small, and he glides on the clouds of his mother’s arms like Daenerys on her dragon. Due to his qualities of being so fresh and little, the members of the gang(his brothers) call him “microsoft”. Don’t be deceived by his qualities! he is the most dangerous member of the crew, the baby-faced assassin.</p><p>His other two brothers come in with so much enthusiasm, and the parade ends with the mother’s younger sister. She doesn’t come in empty, she carries a very important object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZM3hK6Pk06LKlQvtFXLaYg.jpeg" /><figcaption>The toolbox</figcaption></figure><p>If you’re an Engineer or your certificate told you you’re an Engineer you’ll know that nothing gets started without the toolbox. The object above is strictly for the baby faced assassin. It contains his towels, water bottle, biscuits etc. and only his mum has the security clearance to access the bag. Unfortunately for you, they find an empty pew right in front of you, they fill it up and are ready for service.</p><h3>30 MINUTES INTO SERVICE</h3><p>The baby faced assassin(worst case scenario: between two and three years) has had enough of the serenity. It’s getting at him, he has to do something, and he has to do it real fast. His mother hands him the last stick of his biscuits and then he breaks it, throws it to the floor(WAR START!). He takes his water bottle, opens it and then pours the water in it on the ground. His mother is trying to calm him down, and then he takes off her head tie and slaps the fathers face a couple of times.</p><p>This sends a signal to his wing men, his two brothers know its time for war. They are tired of sitting, they need to leave the pew. They have been giving all manner of excuses,(“I want to wee”, “I want to go!”) but their mum wasn’t having it. Now it’s time for brute force, and if you are a captain, you’ll know nobody wins the war without conquering the flanks. They attack the left and right side of the pew, like a strike force of Ronaldo and Mbappe, they mount all the pressure they can.</p><p>Meanwhile, the mum like a coach on the sidelines, is dishing out instructions and making substitutions (“You,stop that”, “You, go there”,”You, shut up”) and her assistant is lost.</p><p>The Man of the house has been trying to focus on the word of God for the season, It’s almost time to pay fees for the new term, so you really can’t blame him. But he has had enough, so he dishes out slaps here and there, and yells at them. In the twinkling of an eye, The war is over!</p><h3>30 MINUTES TO THE END OF THE SERVICE</h3><p>Baby faced assassin is sleeping, looking all tired and distressed after the long fought war. His brothers are in their sits, sober, knowing they were lucky to make it out alive. The impact of the slaps came like bullets, but they leave church knowing one thing, “Another Sunday will come, and we will try again!”.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8a460bb6e3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Effects of Redis on an API Server]]></title>
            <link>https://medium.com/hackernoon/effects-of-redis-on-an-api-server-1e228a624f15?source=rss-dba5ed7f7576------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e228a624f15</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[api-server]]></category>
            <category><![CDATA[redis-api-server]]></category>
            <dc:creator><![CDATA[Paschal]]></dc:creator>
            <pubDate>Wed, 29 Aug 2018 16:26:11 GMT</pubDate>
            <atom:updated>2018-08-29T21:40:38.598Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6K5vmzalJUxn44v3cm6wBw.jpeg" /><figcaption>Photo by thomas kvistholt on <a href="https://unsplash.com/search/photos/robots?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Hello! We will be looking at the effects of redis on the performance of our API server. <a href="https://redis.io/">Redis</a> (Remote dictionary server) can be used as a database, a cache and several other things. For this project, we will be using Redis for caching.</p><h3><strong>Why do we need to cache ?</strong></h3><ul><li>It helps us reduce the overhead due to the amount of API requests and responses the server has to handle.</li><li>The users request or the servers response will be served quicker, due to reduced latency.</li></ul><p>Redis basically will help us cache data, and afterwards serve the data when that particular request is made.</p><p>For example, If we are working with a server that allows users sign up and then shop on the site, we know that the “shopping data”(adding items to the cart, adding money to the wallet, removing items from the cart, paying for orders using different gateways etc.) is much more dynamic compared to the profile of the user, which was formed using the information upon signup. The “signup data”(user’s name, user’s address, user’s mail etc.) is less likely to change and this kind of data can be stored in the cache and then periodically the cache can be updated or refreshed. This will help increase time efficiency. If a server attempts accessing the network(Internet) by querying a db or an API, is much more CPU intensive than accessing the L1 cache or the RAM. This means it will be much more efficient to access the cache, than to keep querying a db.</p><h3>Create the Server</h3><p>The stack for implementing this server will be:</p><ul><li>Node JS + Express</li><li><a href="https://www.postgresql.org/">PostgreSQL</a> (Database)</li><li>Redis (Cache)</li></ul><p>Firstly, we download the <a href="https://www.postgresql.org/">PostgreSQL</a> installer, which comes with psql(SQL shell) and pgAdmin(Make sure to take note of the ‘user’,‘password’ and ‘port’ during installation). To be clear, I am using the windows OS for this project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nv0NwYq0rWG0-XqGcmOujw.png" /><figcaption>A snippet of the pgAdmin home page.</figcaption></figure><p>We can create a database for ourselves, we just have to open the pgAdmin application which runs in the browser and then click on ‘Servers/postgreSQL/Databases’, then right-click on ‘Databases’ and then ‘create’ to make a new one. For this project, the name is ‘users’.</p><p>We can then create a table by clicking on ‘users/Schemas/Tables’ and then right-click and then ‘create’ to make a new one. The name of this table is ‘data’.</p><p>We can now create our folder using the express generator.</p><pre>express myapi</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df5ac00c6fabfb4e85796c0e5bd2f115/href">https://medium.com/media/df5ac00c6fabfb4e85796c0e5bd2f115/href</a></iframe><p>The ‘myapi’ folder should have all these files in it, and lets do well to ensure our routes are working fine.</p><h3>index.js</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/868bde435c2a615d9fe1ddad9e88c5cf/href">https://medium.com/media/868bde435c2a615d9fe1ddad9e88c5cf/href</a></iframe><p>This file just creates the routes for our basic CRUD application and includes the crudController, which has functions to handle all the routes.</p><h3>crud-controllers.js</h3><p>Firstly, we need to install some packages.</p><pre>npm install --save redis response-time pg-promise</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb05495d97ba3bf7beaf21c35d66b872/href">https://medium.com/media/eb05495d97ba3bf7beaf21c35d66b872/href</a></iframe><p>This file just creates the redis client, and then sets the ‘initialization options’ for connecting to the postgreSQL db.</p><p>To connect to the db, we need to get the URL for the db, which is usually in this form:</p><pre>postgresql://[user[:password]@][netloc][:port][/dbname]</pre><p>By default:</p><ul><li>user : <strong>postgres</strong></li><li>netloc : <strong>localhost</strong></li><li>port : <strong>5432</strong></li><li>dbname : The name of our db is <strong>users</strong></li><li>Then you can input the password you set upon installation.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/763b88ed8a15d2c3379d5d70201931d0/href">https://medium.com/media/763b88ed8a15d2c3379d5d70201931d0/href</a></iframe><p>We installed ‘pg-promise’ which helps us work with our postgreSQL using promises and the ‘initializationOptions’ help us check for errors.</p><p>Then we connect to our db using the ‘connectionString’. If everything was done correctly, we should see “success!!!” in our terminal when we start the server.</p><p>Finally, we will be using the redis client on the ‘/get/:id’ route which is controlled by ‘crudController.getSingle’. We can see this route on our index.js file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7288c0a6da35bf19856b394aff8095bd/href">https://medium.com/media/7288c0a6da35bf19856b394aff8095bd/href</a></iframe><p>Firstly, in the getSingle function we get the id of the user. Since redis works based on keys and values, we<strong> set </strong>keys and get <strong>values</strong>.</p><p>So we check if we can get any value from the user’s ID, if there is a result, we send a response saying the data was gotten from the redis-cache. If there was no result, we query the db and then when the result is gotten we now store it in our cache.</p><p>This will surely happen during every new request, then after the first request the data will be saved. We used <strong>setex </strong>so that we can set the <strong>key </strong>which is the userID, and also the expiry time which is <strong>60</strong> seconds. So<strong> setex </strong>is a combination of SET and EXPIRY and then lastly we added the data as the <strong>value. </strong>So 60 seconds is the TTL(Time to live) for this key-value pair.</p><p>Now, we can check the time it took for the API server to query the db, and then how long it took to get the data from the cache.</p><p>We need to add the response-time package to the app.js file</p><pre>//At the top<br>var<em> </em>responseTime<em> </em>=<em> require</em>(&#39;response-time&#39;);<br>.<br>.<br>.<br>//Above the routes<br>app<em>.</em>use(responseTime());</pre><p>The response-time package adds a ‘X-Response-Time’ key to our header and shows us the time taken.</p><p>Now, we can go and add data to our table ‘data’, so that we can have data to play with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*NVl7Z_cVB1LsZnytekQYaw.png" /><figcaption>A snippet of the DB.</figcaption></figure><p>So let us start up our server using <strong>npm start </strong>and then go to our browser, and type in the URL <strong>“localhost:3000/get/2” </strong>since we have items with ids 1,2 and 3.</p><p>Then we can open up the chrome developer tools, go to the network and click on the id.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zo5JTHXqgqGy4Kc4Z3WLBg.png" /><figcaption>Response from DB</figcaption></figure><p>So since this is the first request, it wasn’t in the cache and then the db was queried directly. At the bottom of the screen, we can see the X-Response-Time to be <strong>124.092ms.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LWT2pw3PQXC0xY-rm_LfIw.png" /><figcaption>Response from cache</figcaption></figure><p>From the response, we can see the source is the redis-cache and the X-Response-Time is <strong>1.224ms.</strong></p><p>So, we can see caching is much more effective, especially when we have many more users and when the db is no longer hosted locally.</p><p><em>Thank you very much for reading!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e228a624f15" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/effects-of-redis-on-an-api-server-1e228a624f15">Effects of Redis on an API Server</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Little hacks around API’s colossal woes]]></title>
            <link>https://codeburst.io/little-hacks-around-apis-colossal-woes-e57496941e82?source=rss-dba5ed7f7576------2</link>
            <guid isPermaLink="false">https://medium.com/p/e57496941e82</guid>
            <category><![CDATA[spotify-api]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[spotify]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Paschal]]></dc:creator>
            <pubDate>Wed, 28 Mar 2018 13:54:17 GMT</pubDate>
            <atom:updated>2018-03-28T13:54:17.632Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*6K4eQYf0R7cPCzukMCtu7Q.png" /></figure><p>API’s are application programmable interfaces that allow you use a part of another software on your own software. It is like the middleware which allows two softwares communicate.</p><p>Obviously, we have all the details and facts about working with API’s but today we will be learning a few hacks using <a href="https://developer.spotify.com/web-api/">Spotify’s API</a>.</p><p>We can read up the <a href="https://beta.developer.spotify.com/documentation/">documentation</a> for the spotify API if we want to, but basically the user must be authenticated first before he can query the API.</p><p>To successfully complete this project, we must <a href="https://beta.developer.spotify.com/dashboard/applications">create</a> or register our software on spotify. When this is done, we need to get our</p><ul><li>Client ID</li><li>Client Secret</li></ul><p>We also need to set our Callback URI, which is the URI the user will be redirected to after authentication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lm7gROVCPtsJk4peMhw56A.png" /><figcaption>A snippet of setting the API’s redirect URI’s</figcaption></figure><p>Now to our project, we will have three html files:</p><ul><li>index.html</li><li>login.html</li><li>spotify_oauth_callback.html</li></ul><p>We will be working with the ‘search’ endpoint from the spotify’s API. To query this endpoint successfully, we need to:</p><ul><li>Query the ‘authorize’ endpoint with our Client ID and then get our access token in return.</li><li>Then query the ‘search’ endpoint with our access token and get the response.</li></ul><p>This sounds easy enough, so let’s get started.</p><h3><strong>index.html</strong></h3><p>The index.html file will have the iframe which will allow us link to another page. We are doing this because we want to pass the access token between pages without being disturbed by the ‘access-control access-origin’ CORS thingy.</p><p>Our index.html will look like this:</p><pre>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;Hello!&lt;/title&gt;<br>    &lt;meta charset=&quot;utf-8&quot;&gt;<br>    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;h1&gt;Little hacks around API&#39;s colossal woes&lt;/h1&gt;<br>    &lt;iframe src=&quot;/login.html&quot;&gt;&lt;/iframe&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><h3><strong>login.html</strong></h3><p>The login.html, will have javascript embedded in it. This is not the perfect method but the javascript is very little.</p><p>firstly, the markup will be something of this sort:</p><pre>&lt;a href=&quot;<a href="https://www.glitch.com/">https://www.glitch.com</a>&quot;&gt;Connect Spotify&lt;/a&gt;<br>&lt;img src = &quot;first.jpeg&quot; id=&quot;images&quot;  &gt;<br>&lt;p id=&quot;show&quot;&gt;&lt;/p&gt;</pre><p>I did this on glitch, but you can use any URI as the link for the href. The ‘img’ and the ‘p’ tags will contain the image and the name of the album we will be fetching.</p><p>Finally, Javascript. Before we continue, let us ensure we link jQuery to our login.html page.</p><pre>//We declare our accessToken variable</pre><pre>let accessToken;</pre><pre>//An event listener, for when the &#39;Connect spotify&#39;link is clicked.</pre><pre>document.querySelector(&#39;a&#39;).addEventListener(&#39;click&#39;,(event)=&gt; {<br>        event.preventDefault();<br>        let strWindowFeatures =  &quot;location=yes,<br>                                  height=570,<br>                                  width=520,<br>                                  scrollbars=yes,<br>                                  status=yes&quot;;<br>        let clientId = &#39;YOUR CLIENT ID&#39;;<br>        let scopes = &#39;user-read-private user-read-email&#39;;<br> });</pre><p>When the link is clicked, we prevent the default response(which is opening ‘glitch.com’)from occurring and then we declare the measurements for the window that will be coming up. The Client ID given to you when the app was created, should be replaced with the ‘YOUR CLIENT ID’ string. The scopes are also from spotify which allows them access the users profile.</p><p>Still on the event listener, we declare the Authentication endpoint from spotify as the URL.</p><pre>var URL = `<a href="https://accounts.spotify.com/en/authorize?client_id=${clientId}&amp;response_type=token&amp;${scopes">https://accounts.spotify.com/en/authorize?client_id=${clientId}&amp;response_type=token&amp;${scopes</a> ? &#39;&amp;scope=&#39; + encodeURIComponent(scopes) : &#39;&#39;}&amp;redirect_uri=https%3A%2F%2Fsolar-geography.glitch.me%2Fspotify_oauth_callback.html&amp;show_dialog=true`;</pre><pre>        var win = window.open(URL, &quot;_blank&quot;, strWindowFeatures);</pre><pre>        window.addEventListener(&#39;message&#39;,function(event) {<br>          console.log(&#39;received response:  &#39;, event.data);<br>                      },false);</pre><p>Ok, lets explain the URL.</p><ul><li>The first part before the ‘?’ is simply the endpoint.</li><li>The ‘client_id’ is the Client ID given to us by spotify, we want an access token as the response, so that’s the ‘response_type’ .</li><li>The ‘scopes’ are what we have specified above but if there is none an empty string should be used.</li><li>The ‘redirect_uri’ is the URI we specified when we were creating ‘Redirect URIs’. The URI above is simply ‘https://solar-geography.glitch.me/spotify_oauth_callback.html’ but it is encoded and finally we set the ‘show_dialog’ to true.</li></ul><p>Then we open a window, with the URL as the link and the ‘strWindowFeatures’ for the design of the window.</p><p>A ‘message’ event listener is added to listen for any message sent to the window. After we are authenticated, an access token is supposed to the attached to the Callback of the URI. The message the iframe sends to the window is what the event listener listens to.</p><p>For this to work, we must be sending a message from the page that has the access token embedded in its URI. This leads us to the spotify_oauth_callback.html</p><h3><strong>spotify_oauth_callback.html</strong></h3><p>This is the page that will be loaded after authentication, because this is our ‘redirect_uri’. This page will hold our access token, and we want to pass this token to the other page.</p><pre>&lt;p&gt;loading...&lt;/p&gt;<br>    &lt;script&gt;<br>window.opener.postMessage({data: window.location.hash.slice(1)}, &#39;<a href="https://solar-geography.glitch.me&/#39;">https://solargeography.glitch.me&#39;</a>);<br>window.close()<br>    &lt;/script&gt;</pre><p>Normally, we should have something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZdnsFPhoohdR9p3YflUfxw.png" /></figure><p>When ‘Connect spotify’ is clicked…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F3N08fa-4o0cYI1VDbdPzw.png" /><figcaption>A snippet for the spotify authentication</figcaption></figure><p>When ‘OKAY’ is clicked, we get redirected and then the postMessage function is called. The postMessage sends data, this data is the access token which is the ‘window.location.hash’. The <a href="https://www.w3schools.com/jsref/prop_loc_hash.asp">window.location.has</a>h gives us the part of the URI after the ‘#’ which is where our access token is located. The window.location.hash comes with the ‘#’ alongside, so we can exclude it by</p><pre>window.location.hash.slice(1)</pre><p>Then, the other parameter passed into the postMessage function is the origin the other page must have before the message is sent. Using ‘ * ’ means that the message will be sent to any URL which is not secure.</p><p>Then we close the window.</p><p>Going back to the login.html, we can now get the access token we have sent from the spotify_oauth_callback.html</p><h3><strong>login.html cont’d</strong></h3><p>Now, we will add to the ‘message’ event listener.</p><pre>window.addEventListener(&#39;message&#39;,function(event) {</pre><pre>          console.log(&#39;received response:  &#39;, event.data);</pre><pre>          //THE ACCESS TOKEN IS REPRESENTED BY event.data.data</pre><pre>          accessToken = JSON.stringify(event.data.data);</pre><pre>          getData();      <br>},false);</pre><p>If you want, you can log the output of the whole ‘event’ object on the console, but the accessToken is event.data.data</p><p>Then the getData() function is called, which will help us query the search API.</p><p>Normally, the access token looks like this:</p><p>‘access_token=92388&amp;duration=3600’. So we have to split it with the ampersand and the equals sign so that it looks like ‘92388’ and then the token is passed as an authorization header in the AJAX request.</p><p>Finally, the data sent includes the artist which is ‘rihanna’ and we want her ‘albums’. The response comes and then we get the album cover and the name of the first album.</p><pre>let getData = ()=&gt;{</pre><pre>       console.log(accessToken,&#39;acessToken&#39;);</pre><pre>       accessToken = accessToken.split(&#39;&amp;&#39;);</pre><pre>       let accessPoint = accessToken[0].split(&#39;=&#39;)[1];</pre><pre>       console.log(accessPoint);</pre><pre>       $.ajax({</pre><pre>            url:&#39;https://api.spotify.com/v1/search&#39;,</pre><pre>            headers: {</pre><pre>                  &#39;Authorization&#39;:&#39;Bearer &#39; + accessPoint</pre><pre>             },</pre><pre>             data:{</pre><pre>                  q:&#39;rihanna&#39;,</pre><pre>                  type:&#39;album&#39;,</pre><pre>                  market:&#39;from_token&#39;</pre><pre>             },</pre><pre>       success: (res)=&gt;{<br>                 //showing the response</pre><pre>                 console.log(res);<br>                 <br>                 //adding the album image and name</pre><pre>                 $(&quot;#images&quot;).<br>                  attr(&#39;src&#39;,res.albums.items[&#39;0&#39;].images[&#39;0&#39;].url);</pre><pre>                  $(&quot;#show&quot;).html(res.albums.items[&#39;0&#39;].name);                     }</pre><pre>})</pre><pre>}</pre><p>Our result should be something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dyvo1ry9PXRcsYYw6b4g1g.png" /><figcaption>Rihanna’s album cover and name</figcaption></figure><p>If you had any issues along the way, you could check out the glitch link below for clarity.</p><p><a href="https://glitch.com/edit/#!/solar-geography?path=login.html:25:38">https://glitch.com/edit/#!/solar-geography</a></p><p>I want to appreciate Hugh Rawlinson, for help on this project.</p><p><strong><em>Send me a DM on </em></strong><a href="https://twitter.com/_Obbap"><strong><em>Twitter</em></strong></a><strong><em> if you have any questions. If you learnt anything, please clap. Thank you.</em></strong></p><figure><a href="http://bit.ly/codeburst"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3hPOj27LTt0ZPn5TQuhZg.png" /></a></figure><blockquote>✉️ <em>Subscribe to </em>CodeBurst’s<em> once-weekly </em><a href="http://bit.ly/codeburst-email"><strong><em>Email Blast</em></strong></a><strong><em>, </em></strong>🐦 <em>Follow </em>CodeBurst<em> on </em><a href="http://bit.ly/codeburst-twitter"><strong><em>Twitter</em></strong></a><em>, view </em>🗺️ <a href="http://bit.ly/2018-web-dev-roadmap"><strong><em>The 2018 Web Developer Roadmap</em></strong></a><em>, and </em>🕸️ <a href="http://bit.ly/learn-web-dev-codeburst"><strong><em>Learn Full Stack Web Development</em></strong></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e57496941e82" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/little-hacks-around-apis-colossal-woes-e57496941e82">Little hacks around API’s colossal woes</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Heroku’s handshake with mlab]]></title>
            <link>https://medium.com/hackernoon/herokus-handshake-with-mlab-7fea651fa8c2?source=rss-dba5ed7f7576------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fea651fa8c2</guid>
            <category><![CDATA[herokus-handshake]]></category>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[mlab]]></category>
            <dc:creator><![CDATA[Paschal]]></dc:creator>
            <pubDate>Thu, 22 Feb 2018 13:24:55 GMT</pubDate>
            <atom:updated>2018-02-22T13:24:55.448Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*etPIUGEIegJtbaRqYVarCQ.jpeg" /></figure><p>A Platform-as-a-Service(PaaS) saves us the time required to set up virtual servers, makes scalability easier and depletes the cost implication of setting up the servers.</p><p>Initially, setting up a server in the cloud required connecting and configuring all types of components but the introduction of Serverless,Docker,Heroku and the likes have allowed us focus on only the application.</p><p>We will be merging our MongoDB cloud service(mlab) with our PaaS(Heroku). This is important because while using PaaS, it allows us concentrate on developing and managing our applications without being perturbed by the thought of maintaining the infrastructure.</p><p>To go through this process successfully, we need to have:</p><ul><li><a href="https://devcenter.heroku.com/articles/heroku-cli#download-and-install">Heroku CLI</a></li><li><a href="https://git-scm.com/download/win">Git bash</a> (of course)</li><li><a href="https://www.mlab.com/login/?r=%2Fdatabases%2Fheroku_3wwgk424#users">An mlab account</a></li><li><a href="https://id.heroku.com/login">A Heroku account</a></li></ul><p>Now we have everything up and running, we can create a new app on our Heroku account. For the sake of this project, the name of the app is ‘mediumapp11’.</p><p>Then we create a database on mlab, with the name ‘mediumapp11’. When we have our database up and running, we can add a database user and then we will see our MongoDB URI above. This will help us connect to our database from our localhost.</p><p>We will have something of this nature:</p><pre>mongodb://&lt;dbuser&gt;:&lt;dbpassword&gt;<a href="http://twitter.com/ds041678">@ds0*1*7</a>*.mlab.com:41678/mediumapp11</pre><p>Where the ‘dbuser’ tag is the username of the user you created and the ‘dbpassword’ is the password of the user.</p><p>Now on our local host, we can create a ‘mediumapp11’ folder and then do this:</p><pre>heroku addons:add mongolab --app mediumapp11</pre><p>Where ‘mediumapp11’ is located, the name of your app will go there. When this is done, we should find mlab as an addon in our Heroku project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*9VwACTUCoixVQkuCiVQuWQ.png" /></figure><p>Now, we can finally create a ‘mediumapp11.js’ file. We will need the mongoose dependency to define our schema and http.</p><pre>const mongoose = require(&#39;mongoose&#39;);</pre><pre>const http = require(&#39;http&#39;);</pre><pre>const Schema = mongoose.Schema;</pre><p>Then now, we can define our schema ,create a document which is the instance of our model and then specify the URI we had gotten from mlab.</p><pre>let Team = mongoose.model(&#39;Team&#39;, TeamSchema);</pre><pre>let db = mongoose.connection;</pre><pre>let dbUrl = &#39;mongodb://mediumapp11:mediumapp11<a href="http://twitter.com/ds041678">@ds041678</a>.mlab.com:41678/mediumapp11&#39;;</pre><p>Then, we can listen for errors and if there is none we connect to our URI and save a particular document.</p><pre>db.on(&#39;error&#39;, function () {console.log(&#39;error&#39;);});</pre><pre>mongoose.connect(dbUrl, function (err) {</pre><pre>if (err) {  return console.log(&#39;there was a problem&#39; + err);  }</pre><pre>console.log(&#39;connected!&#39;);</pre><pre>var team = new Team({ name: &#39;Jehovah&#39;  });</pre><pre>team.save(function (error, data) {</pre><pre>if (error) {console.log(error);} </pre><pre>db.close();</pre><pre>process.exit();</pre><pre>});</pre><pre>});</pre><p>Now, we should ensure we replaced the ‘&lt;dbuser&gt;’ with ‘mediumapp11’ and the ‘&lt;dbpassword&gt;’ with ‘mediumapp11’ and then we can run the app</p><pre>node mediumapp11.js</pre><p>We can now refresh our mlab, then go to documents and then we will find our our document saved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2RO_C2lzCw9nYehAfDnRSA.png" /></figure><p>If you learnt anything, let me know by 👏👏👏.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fea651fa8c2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/herokus-handshake-with-mlab-7fea651fa8c2">Heroku’s handshake with mlab</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NETWORKING BASICS(PART TWO)]]></title>
            <link>https://medium.com/@_Obbap/networking-basics-part-two-1d5c6e0c2cfd?source=rss-dba5ed7f7576------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d5c6e0c2cfd</guid>
            <category><![CDATA[computer-networking]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[web-programming]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Paschal]]></dc:creator>
            <pubDate>Tue, 10 Oct 2017 10:56:29 GMT</pubDate>
            <atom:updated>2017-10-10T10:56:29.240Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*xNDaj598J4y__0JQRyEMvQ.jpeg" /></figure><p><strong>NETWORKING BASICS(PART TWO)</strong></p><p><strong>IP ADDRESSING</strong></p><p>Ok! Last week, we saw how to get the IP address that has been assigned to us on a particular network and how to know the default gateway IP address. So today, we want to know exactly what an IP address is.</p><p>An IP address is simply an address assigned to a device connected to a network. IP addresses are basically in two versions, we have the ipv4 and ipv6 addressing systems. Ipv4 is a 32-bit addressing system and it’s what the majority still use. For knowledge sake, I think the ipv6 is a 128-bit addressing system and was created because the number of devices connected to the internet were becoming outrageous and so various means have been generated to curb the issue.</p><p>IP means Internet Protocol, I know right, who doesn’t know that? The IP address comes in on the network layer. Now let me explain this carefully, a router or a gateway, can have four IP addresses. Imagine if I have four class rooms, and I have four<strong> switches</strong>. Let’s think of the switch as an extension box where everybody computer is connected to. When I say an IP address has 32 bits, this means it is represented as 11111111.11111111.11111111.11111111, this is when all the bits are turned on. So if this is converted to decimal, we have 255.255.255.255. You can look up converting binary numbers to decimal if you want to understand how.</p><p>So we can have 10101010.10000000.11111111.00101010, as far as they are represented in 32 bits. Basically, we have three classes of IP addresses. Classes A, B and C. There are other classes, for reserved purposes. So for every network, we have a network address and a broadcast address. A Class A network, starts from 1–127(The first decimal). This means if you see an IP address with 10.0.0.128, we know that it’s a Class A network. A Class A network, uses the first 8 bits for the network and the last 24 for the hosts. The hosts are the servers, switches, laptops, phones etc. on the network. So the default way a Class A network will be represented will be 255.0.0.0, This is the default subnet mask. This means by default, the first 8 bits are already used for the network and the last 24 bits are empty and can take in hosts. To calculate the number of hosts this network can take by default, we use the formula: 2 ^ X — 2. Where X is the number of bits that are turned off or the number of bits available for hosts. And then we subtract it from two, because we need to reserve those two addresses for the network address and the host address. A Class B network will have its first decimal ranging from 128–191. So an IP address 172.16.177.2 is in a Class B network. It has a default subnet mask of 255.255.0.0. This means 16 bits are free for the hosts. So we have less space for the hosts on a Class B network. A Class C network, has its starting decimal from 192–224. This means an IP address, 196.16.12.1 is under a Class C network. The default subnet mask is 255.255.255.0, so just the last 8 bits are reserved from the hosts. You can read this again, to make sure you get it, also you can use Todd Lammle’s CCNA Routing and Switching guide.</p><p>Now I think I can go back to my example. Just to make it clear, every device on a network, is assigned an IP address. Your websites, have IP addresses that are converted using DNS servers. Your local host has a loop back address, 127.0.0.1 most times. Your laptop has its Ethernet port coming with an automatically configured IPv4 address. So everything on the network has an IP address. Okay lets see a practical example. Since i am connected to the internet, that means Google can be reached from my network. This can be confirmed because i can ping Google . You can run your terminal as administrator and input:</p><pre>ping google.com</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5I0NUMBcigywdg0Fh59TNQ.png" /></figure><p>So we sent 4 packets and we lost none. This means i can communicate with the google server. Now the IP address of the google server is shown there ,172.217.23.46 even if in reality, this IP address wont be the actual IP address of the google server for security purposes. If their IP address is left exposed, it could be subject to brute force attacks from several invaders. Okay! but i am sitting in my house in Lagos state, Nigeria. So how did i communicate with the google server. There is a command used to trace the routes our packets took. Lets go to our terminal</p><pre>tracert google.com</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XLzuHpUrh3cr3VNXYIrEZA.png" /></figure><p>This will take a little time, but here is my result!</p><p>now, the first path to <a href="http://google.com/">Google</a> is the router in my house. Firstmile i think, is the ISP to the estate. You can see that it is a class C network, because it needs just a few hosts. The default gateway address, that is the address of my router is 192.168.10.1. The gateways are assigned with the first IP address available, which is usually ‘.1’ and this is mostly static. This is done in order to get rid of any mix up, because the DHCP server can reassign a particular IP. So from my router, the next IP is on a Class A network. Maybe, this is also Firstmile’s network. Then we see google-Lagos and then we see the final address. To confirm, you can go ahead and type the google IP address on your web browser and you will be taken to <a href="http://google.com/">Google</a>. The other IP addresses might not show anything, because they might not be web servers that you get web pages from. like the router in my house, will return a page that has to deal with the configurations of the network. I think we will take the class room example next week.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d5c6e0c2cfd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>