Realtime Exchange Rates With Currencylayer

By Chimezie Enyinnaya

Ever wanted an accurate and reliable currency data that can be easily integrated into your business; be it CRM, ERP, accounting applications etc., built in any programming languages? Then say hello to currencylayer.

In this article, I will show you how to use two of currencylayer’s services: live exchange rates and historical exchange rates.

What is currencylayer?

Currencylayer provides a reliable exchange rates and currency conversion for your business. It does these by providing an easy to integrate REST API with real-time and historical exchange rates for 168 world currencies and precious metals, delivered in universally usable and easily parseable JSON format, and compatible with any application.

The universal real-time exchange rate data solution

In addition to providing update to date real-time exchange rates, currencylayer also provides historical exchange rates for all of their supported 168 world currencies. They provide historical exchange rates for way back as the past 16 years.

So what makes currencylayer perfect for your business? Well, here are some reasons:

  • Reliable forex rates
  • Easy-to-integrate API
  • 256-bit HTTPS
  • Advanced data coverage
  • Real-time updates
  • Extended usage statistics
  • Easy on your budget
  • Interactive documentation

Did I mention that you can use most of these services completely for free? Sure you can! currencylayer has a free plan. With the free plan, you can make update to 1,000 API requests and the data are updated every hour.

Getting started

To start using the services provided by currencylayer, you need to first create an account with them. So head over to the subscription plans page and signup for a free plan.

Once you have signed up, you will be presented with a 3-step quickstart guide. Step 1 contains your Access Key, which you will use to interact with ****the currencylayer API. In step 2, you are presented with the base URL of the currencylayer API:


http://apilayer.net/api/

Take note of your access key and the base URL as we’ll be using them in the next section.

Fetching live exchange rates

To get live exchange rates, we need to make request to the live endpoint of the currencylayer API. That is:


http://apilayer.net/api/live

We need to pass our access key to the above URL.

The sample code in this article will be in Node.js and using Axios as the HTTP client:

const axios = require('axios')

const ACCESS_KEY = 'YOUR_ACCESS_KEY'

axios.get(`http://apilayer.net/api/live?access_key=${ACCESS_KEY}&currencies=USD,EUR,GBP,AUD,NGN`).then(response => {
    console.log(response.data)
})

Here, we specify we want to get the exchange rates for five currencies: USD, EUR, GBP, AUD, and NGN. By default, USD will be used as the source. That is, the currency to which all exchange rates are relative. We can as well specify as different source:


http://apilayer.net/api/live?access_key=YOUR_ACCESS_KEY&source=GBP

Below is the response gotten from the above request:

{
  "success": true,
  "terms": 'https://currencylayer.com/terms',
  "privacy": 'https://currencylayer.com/privacy',
  "timestamp": 1526743687,
  "source": 'USD',
  "quotes": {
     "USDUSD": 1,
     "USDEUR": 0.849404,
     "USDGBP": 0.74245,
     "USDAUD": 1.331041,
     "USDNGN": 358.000344
  }
}

The response is pretty straightforward. The exchange rates are inside the quotes object.

Fetching historical exchange rates

We have seen how to get live exchange rates. Now, let’s see how to fetch exchange rates from the past. For this, we make request to the historical of the currencylayer API, passing in our access key and a date in the past:

const axios = require('axios')

const ACCESS_KEY = 'YOUR_ACCESS_KEY'

axios.get(`http://apilayer.net/api/historical?access_key=${ACCESS_KEY}&date=2010-05-19&currencies=USD,EUR,GBP,AUD,NGN`).then(response => {
    console.log(response.data)
})

Here, we specify we want to get the exchange rates for a particular date (2010-05-19) in the past.

Below is the response gotten:

{
  "success": true,
  "terms": "https://currencylayer.com/terms",
  "privacy": "https://currencylayer.com/privacy",
  "historical": true,
  "date": "2010-05-19",
  "timestamp": 1274313599,
  "source": "USD",
  "quotes": {
    "USDUSD": 1,
    "USDEUR": 0.809694,
    "USDGBP": 0.69632,
    "USDAUD": 1.184999,
    "USDNGN": 152.073107
  }
}

In addition to the standard result sets, an historical API response contains an historical key with a value of true and the specified date.

Conclusion

In this article, we have seen what currencylayer is, the service it provides and some reasons to use it in your business. Though, we only looked at two of the services currencylayer provides. In addition to live and historical exchange rates, currencylayer can also handle currency conversion and lot more.

For more information about currencylayer, do check out their website and their easy to understand documentation.

Source:: scotch.io

Introduction To Koa - The Future of Express

By Olayinka Omole

Express is one of the most popular Node.js frameworks out there. With about about 4+ million weekly downloads, Express has clearly made its mark in the world of Node.js and JavaScript.

Koa is a newly popular web framework created by the team behind Express. It aims to be a modern and more minimalist version of Express. Some of its popular characteristics are its support and reliance on new JavaScript features such as generators and async/await. Koa also does not ship with any middleware though it can easily be extended using custom and existing plugins.

In this article, we will examine the Koa framework and build a simple app to get familiar with its functionality and philosophy.

Requirements

To follow along with this tutorial, you would need the following installed:

You also need to have a working knowledge of JavaScript and ES6 syntax.

Setup and Configuration

Let us get started by setting up our project. First, we will create a new directory for our project. This can be done by copying and running the command below in you terminal:

$ mkdir koala

⚠️ Note: You can give your project any name, but in this article we’ll be using koala as our project name and directory.

At this point, we have created our project directory koala. Next, we will initialise our node project from inside the directory. You can do so by running the commands below:

$ cd koala
$ npm init koala 

After running the npm init command, follow the prompts and fill in the details of your project. At the end of this, you will have a package.json file with the information you enetered while prompted.

💡 Tip: You can run npm init -y to create a package.json file with default values.

Next, we will run this command to install Koa:

$ npm install koa --save

💡 Tip: Depending on the version of Node you have running you may not need to add the --save flag. This flag tells older versions of Node to add the installed library (in this case Koa) to the dependencies list in our package.json file. On newer Node versions, you can simply run npm i koa to install Koa.

Building Out Our App

Creating a Koa Server

During the initialisation of our project, we were prompted to enter the entry point of our application. In this article, we will use index.js which was the default value as our entry point.

First, we will create the index.js file, this can be done in several ways. For MacOS and Linux users, this can be done by running the below command in your terminal:

$ touch index.js

Using your code/text editor of choice, we will open our project and copy the below snippet into the index.js file:

 // index.js

'use strict';

const koa = require('koa')
const app = new koa()

app.use(function *(){
  this.body = "Hello World !!!";
});

app.listen(1234)

In the snippet above, we have created a koa application that runs on port 1234. You can run the application using the command:

$ node index.js

And visiting the application on http://localhost:1234.

Routing In Koa.js

As mentioned earlier, Koa.js does not ship with any contained middleware and unlike its predecessor, Express, it does not handle routing by default.

In order to implement routes in our Koa app, we will install a middleware library for routing in Koa, Koa Router. We’ll install it by running:

$ npm install koa-router --save 

To make use of the router in our application, we will amend our index.js file:

// index.js

'use strict';
const koa = require('koa')
const koaRouter = require('koa-router')

const app = new koa()
const router = new koaRouter()

router.get('koala', '/', (ctx) => {
  ctx.body = "Welcome! To the Koala Book of Everything!"
})

app.use(router.routes())
  .use(router.allowedMethods())

app.listen(1234, () => console.log('running on port 1234'))

Above, we have defined a route on the base url of our application (http://localhost:1234) and registered this route to our Koa application.

💡 For more information on route definition in Koa.js applications, visit the Koa Router library documentation here.

Templating In Koa.js

As already established, Koa comes as a very minimalistic framework, therefore, to implement view rendering with a template engine we will have to install a middleware library. There are several libraries to choose from but in this article we will use koa-ejs.

To do so, we will first install the library using:

$ npm install koa-ejs --save

Next, we will ammend our index.js file to register our templating with the snippet below:

// index.js

'use strict';
const koa = require('koa')
const path = require('path')
const render = require('koa-ejs')
const koaRouter = require('koa-router')

const app = new koa()
const router = new koaRouter()

render(app, {
  root: path.join(__dirname, 'views'),
  layout: 'layout',
  viewExt: 'html',
  cache: false,
  debug: true
})

router.get('koala', '/', (ctx) => {
  ctx.body = "Welcome! To the Koala Book of Everything!"
})

app.use(router.routes())
  .use(router.allowedMethods())

app.listen(1234, () => console.log('running on port 1234'))

As seen above, in our template registering, we tell our application the root directory of our view files, the extension of the view files and the base view file (which other views extend).

Now that we have registered our template middleware, we will amend our route definition to render a template file:

// index.js

...

router.get('koala', '/', (ctx) => {
  let koala_attributes = [];
  koala_attributes.push({
    meta_name: 'Color',
    meta_value: 'Black and white'
  })
  koala_attributes.push({
    meta_name: 'Native Country',
    meta_value: 'Australia'
  })
  koala_attributes.push({
    meta_name: 'Animal Classification',
    meta_value: 'Mammal'
  })
  koala_attributes.push({
    meta_name: 'Life Span',
    meta_value: '13 - 18 years'
  })
  koala_attributes.push({
    meta_name: 'Are they bears?',
    meta_value: 'no!'
  })
  return ctx.render('index', {
    attributes: koala_attributes
  })
})

...

Above, our base route renders the index.html file found in the views directory. Our index.html file contains some basic HTML to display our koala attributes. See below:

<!-- views/index.html -->

<h2>Koala - a directory Koala of attributes</h2>
<ul class="list-group">
  <% attributes.forEach( function(attribute) { %>
    <li class="list-group-item">
      <%= attribute.meta_name %> - <%= attribute.meta_value %>
    </li>
  <% }); %>
</ul>

💡 Tip: For more options with using the koa-ejs template middleware, view the library documentation here.

Handling Errors and Responses

Error Handling

Koa handles errors by defining an error middleware early in our entrypoint file. The error middleware must be defined early because only errors from middleware defined after the error middleware will be caught. Using our index.js file as an example, we’ll adjust it to include:

// index.js

'use strict';
const koa = require('koa')
const render = require('koa-ejs')
const koaRouter = require('koa-router')

const app = new koa()
const router = new koaRouter()

app.use( async (ctx, next) => {
  try {
    await next()
  } catch(err) {
    console.log(err.status)
    ctx.status = err.status || 500;
    ctx.body = err.message;
  }
})

...

The above block catches any error thrown during the execution of our application. We’ll test this by throwing an error in the function body of the route we defined:

// index.js

...

router.get('koala', '/', (ctx) => {
  ctx.throw('Test Error Message', 500)
}) 
...

Handling Responses

The Koa response object is usually embedded in its context object. Using our route definition, we will show an example of setting responses:

// index.js

'use strict';
const koa = require('koa')
const koaRouter = require('koa-router')

const app = new koa()
const router = new koaRouter()

app.use( async (ctx, next) => {
  try {
    await next()
  } catch(err) {
    console.log(err.status)
    ctx.status = err.status || 500;
    ctx.body = err.message;
  }
})

router.get('koala', '/', (ctx) => {
  ctx.status = 200
  ctx.body   = "Well this is the response body"
})

Conclusion

In this article, we had a brief introduction to Koa and how to implement some common functionalities in a Koa project. Koa is a minimalist and designed-to-be-flexible framework that can be extended to more functionality than this article has shown. Because of its futuristic approach and similarity to Express, some have even described it as Express 5.0 in spirit.

The entire code from this article is available on Github, and the repository contains some additional concepts not treated here, as they are beyond the scope of the intro. We’d love to hear about what you’ve done with Koa.js. Please share in the comments below!

Source:: scotch.io

Functional-Light JavaScript By Kyle Simpson

Ben Nadel reviews Functional-Light JavaScript by Kyle Simpson. Kyle has an effortless writing style and a knack for breaking down complex concepts into bite-sized pieces which he can then use to construct an increasingly-sophisticated and multi-faceted mental model in the mind of the reader. It is with this measured approach that Kyle introduces us to the world of Functional Programming (FP)….

Source:: bennadel.com

Code Challenge #10: Lazy Loading Animal Memes

By William Imoh

In a bid to lower the load times of a website, several techniques have been developed. One such technique is the lazy loading of images on the page.

TL, DR

As seen above, in this challenge we shall be lazy loading the images on the page. When the page is loaded, only the image placeholders which appear completely in the viewport are fetched.

Hint: The code from this previous challenge could be helpful.

The Challenge

As a performance improvement technique, lazy loading involves the loading of only images whose placeholders come into view.

Implement this lazy loading feature on the provided page containing quite funny animal memes.

  • Placeholder images with smaller dimensions and size are stretched to fit the image size.
  • A larger image is specified using the data-src attribute but isn’t displayed until its placeholder comes in view.
  • The overall size of the page reduces drastically and the page loads several times faster.

From the image above you can also see the individual download of the now visible images in the network tab of the Google Chrome Dev Tools. Now that’s sheer performant development in action!

Requirement

Feel free to complete this challenge using any tool, technique, or technology. However, there is a single requirement for the challenge which is, once the application loads, we require only the images in the viewport to load, while the rest of the images not currently in the viewport loads upon entering the viewport.

Goals for this Challenge

On completion of this challenge, you should be able to:

  • Implement lazy loading on a page to reduce its load time and improve performance.
  • Understand DOM element manipulation using JavaScript.

Bonus

While you are at liberty to complete this challenge with any framework or tool, a bonus will be to animate the transition from the placeholder to the main image.

Resources

To start off quickly with the challenge, a base codepen containing HTML and CSS with Bulma classes for styling has been provided. The base pen consists of the overall layout of the app and images stored in a CDN. Use this to quickly implement the lazy loading feature.
These awesome images used for this demo were sourced from Buzzfeed.

Fork this base codepen to get started

Community

If on the completion of this challenge you wish to showcase your work or receive a review, kindly

  • Post the solution in the comment section of this post.
  • Post it on Twitter using the #scotchchallenge and we will be sure to see it.
  • Join the #codechallenge channel of the Scotch Slack group to interact with others and receive reviews on your submission.

Also, leave your comments, feedback or suggestions in the comment section of this post.

Solution

The solution to this challenge will be released on Monday. Happy coding!!

Source:: scotch.io

How Error Monitoring Helps You Find Bugs BEFORE Users Do

By Nick Harley

One of the biggest distractions to any software team building web and mobile applications is the act of fixing up problems in previously written code.

I’m willing to bet that your personal performance is measured on how much you build, innovative and deploy rather than how much error free code you release or how much technical debt you manage to scoop up on your way. So it always seems like a huge hassle or distraction to be having to go back and fix up bugs.

Trying to diagnose and fix those problems is terribly inefficient too.

Digging through log files, matching time and date stamps and asking non technical users over support tickets what happened and when cause a lot of frustration.

But it doesn’t have to be that way. Here we’ll talk about how effective error monitoring in production means you’ll no longer have to rely on users to report issues and can build higher quality code at the same time.

A few lines of code is all it takes

Using a error monitoring tool like Raygun, we’re be able to get detailed diagnostics for each individual error occurrence and pinpoint the exact line of code causing the problem in seconds.

No more complex debugging or log files to sifter through trying to find the root cause of an issue.

Logging errors vs error monitoring tools

A lot of developers confuse error monitoring tools with traditional logging. And it’s easy to make the relation without understanding the two in more detail.

Dedicated logging tools give you a running history of events that have happened in your application. Dedicated error monitoring tools focus on the issues users face that occur when your app is in production, and record the diagnostic details surrounding the problem that happened to the user, so you can fix it with greater speed and accuracy.

Most error logging activities within software teams remain just that. A log of errors that are never actioned and fixed.

Traditionally speaking, when a user reports an issue, you might find yourself hunting around in log files searching for what happened so you can debug it successfully. Having an error monitoring tool running silently in production means not only do users not need to report issues, as they are identified automatically, but each one is displayed in a dashboard, ranked by severity. Teams are able to get down to the root cause of an issue in seconds, not hours.

Full diagnostic details about the issue are presented to the developer immediately. Information such as OS, browser, machine, a detailed stack trace, a history of events leading up to the issue and even which individual users have encountered the specific issue are all made available.

In short, when trying to solve issues in your applications, you immediately see the needle, without bothering with the haystack.

Error monitoring tools are designed to give you answers quickly. Once you experience how they fit into the software development workflow and work alongside your logging, you won’t want to manage your application errors in any other way.

How easy is it to get started?

The short answer, very.

Most tools work by deploying a small, lightweight script into your production app so that live users are interacting with your application and that’s it!

Errors will start to flow automatically into your dashboard (yes you will have errors – I guarantee that) where you can prioritize which issues to fix first based on the number of users impacted or frequency of the issue.

The Raygun dashboard. Errors are grouped by root cause

There’s so much more!

These sorts of tools are increasing in popularity for software teams due to the transparency they bring around detecting and then resolving software problems that users are experiencing. If you haven’t done so already, why not give them a go.

For developers we are sometimes too far removed from the end user experience to really understand how our code is being received. Error monitoring tools give you a window into how users are really experiencing the software you built.

Championing the push to improve user experiences and make sure quality code is going out the door to customers in your company is a sure fire way to impress your boss and fellow team members.

The next time you are struggling to reproduce issues in your applications, you’ll be glad you have a solution like Raygun in your toolbox.

Don’t just log errors – Use an error monitoring tool and fix them!

Source:: scotch.io

Get to Know React's New Context API

By Sarah Jorgenson

In a world where there are lots of different front-end frameworks, it’s always hard to know which one to pick. Do I want to use the ever popular Angular? Or would diving into VueJS be beneficial to my scope of knowledge?

Then we have ReactJS, a framework created by Facebook that seems to be taking the front-end framework world by storm. Using components, a virtual DOM, and JSX (that’s for a different day!), React seems to cover it all, making it a powerful framework.

The new Context API was recently introduced in React 16.3 as:

A way to pass data through the component tree without having to pass props down manually at every level

Sounds great! Let’s dig in.

Props and State

In React, you have props and state. Two very important things to understand.

Props, short for properties, is the data that is getting passed to the component from a parent component.

State is data that is being managed within the component. So if each component has it’s own state, how do we share that information to another component? You could use props, but props can only be passed between parent and child components.

So what are we to do if we have many layers of components to pass just one bit of information? Also known as, prop-drilling.

Prop Drilling (What the Context API Solves)

Let’s take a look at an example of prop-drilling so we can understand what Context API is solving. In this example, we will see how we can pass information from one component, to the child component, then to that component’s child.

const Lowest = (props) => (
  <div className="lowest">{props.name}</div>
)

const Middle = (props) => (
  <div className="middle">
    <Lowest name={props.name} />
  </div>
)

class Highest extends Component {
  state = {
    name: "Context API"
  }

  render() {
    return  <div className="highest">
      {this.state.name}
      <Middle name={this.state.name} />
    </div>
  }
}

I know the naming isn’t the most real-world, but it helps to demonstrate context’s ability to pass down to nested components. A more real-world scenario is one that happens here at Scotch with our cards: CardGrid -> CardContent -> CardFooter -> LikeButton.

Back to our example, this is how those Highest -> Middle -> Lowest components would get nested:

<Highest>

    <Middle>

        <Lowest>

            {/* we want our content here but dont want to prop pass ALLLL the way down ! */}

        </Lowest>

    </Middle>

</Highest>

Notice how in order for the Highest and the Lowest to talk, they need the Middle to be the messenger?

Well lo and behold, we have React Context that can take care of all the work for us.

React’s Context API

React Context allows us to have a state that can be seen globally to the entire application.

We have to start with the context provider () to define the data you want to be sending around and you need the context consumer () that grabs that data and uses it where called.

With Context, you now have the ability to declare the state once, and then use that data, via the context consumer, in every part of the application.

Sounds incredible, right? Well let’s look at how we could set that up in a simple React application.

Let’s build!

Building a Name Transfer with Context API

Today we are going to be setting up a basic React app. Let’s do an app that passes a name from one component to another component that just so happens to not be the child component! Great! We will have three different levels, one will be the highest component that has the name stored in state, we will have the middle component, and then we’ll have the lowest component.

Our application will send the name in state from the highest to the lowest without having to talk to the middle. Open up whichever code editor you like to use and let’s start coding!

Ok, we will need the react dependency for our app. Go ahead and add that to your dependencies or if you are working in a text editor, do the following steps to install it

  1. Install npm globally on your machine if you do not already have it.
  2. npm install —save react
  3. Check your package.json for the react dependency.

In our main js file, this is where the magic happens. Whenever we are building a React app, you always need to import your dependencies, otherwise that file won’t know to use it. So at the top of the index.js file, let’s import what we need.

import React, { Component } from 'react';

We have our import, now let’s move on to the component. We will want to declare our context in a variable for readability. Under our import let’s do

const AppContext = React.createContext()

Our Layers of Components

Our Highest component will have the state. Our state will have a name that we will want to pass to the Lowest component without having to talk to the Middle component.

class Highest extends Component {
    state = {
        name : “React Context API”,
    }

    render() {
        return <AppContext.Provider value={this.state}>
          {this.props.children}
        </AppContext.Provider>
    }
}

We will build our child component to that calling it the Middle component

const Middle = () => (
  <div>
    <p>I'm the middle component</p>
    <Lowest />
  </div>
)

And the child component to that will be called Lowest

const Lowest = () => (
  <div>
     <AppContext.Consumer>
        {(context) => context.name}
      </AppContext.Consumer>
  </div>
)

Let’s go over this. You will see that we have a state in Highest that we will want to pass to Lowest. We have our static property that will allow us to declare what we want our context to be. In our case, the name “React Context API”.

The Provider is holding on to that data so that when it’s consumed by another component, it knows what to give it. In our Lowest component you will see that we have the Consumer wanting that data without having to first pass it to the Middle component. That component instead just hangs out, declaring that Lowest is it’s child.

When to not use Context

For a simple prop drilling solution that can scale decently, give context a go! For larger scale apps that have multiple (and more complex) states, reducers, etc, Redux may be a better fit.

There is no need to use context all over your application making things a little too messy. Be resourceful with your code, do not just use context to skip extra typing.

Conclusion

The React Context API is pretty awesome. But don’t use it unless you know it will be beneficial to you and your code. Redux might be just fine. Stay away from prop drilling and know that something like context can help you avoid that. It’s a great alternative!

If you want to check out my codesandbox with all the code, you can get it all here!

I hope you enjoyed this article and feel more comfortable with the context side of React. Now go try it out on your own code and see just how powerful it can really be.

Source:: scotch.io

Weekly Node.js Update - #20 - 05.18, 2018

By Tamas Kadlecsik

Weekly Node.js Update - #20 - 05.18, 2018

Below you can find RisingStack‘s collection of the most important Node.js news, updates, projects & tutorials from this week:

Node v8.11.2 (LTS)

Notable Changes:

  • deps:
    • update node-inspect to 1.11.3 (Jan Krems)
    • update nghttp2 to 1.29.0 (James M Snell)
  • http2:
    • Sync with current release stream
  • n-api:
    • Sync with current release stream

Creating a chat with Node.js from the scratch

Let’s create a chat with from the scratch to learn the basics of Socket.IO and what it can offer us, without the use of a database, Ajax or another back-end languag, only JavaScript, Node.js and jQuery.

Weekly Node.js Update - #20 - 05.18, 2018

Training: Designing Microservice Architectures – Berlin

We are going to host a training called Designing Microservice Architectures in Berlin, on June 14th-15th. If you’d like to learn how to break down a monolith into microservices, join us!

An SQLite Tutorial with Node.js

Learn how to use SQLite in combination with JavaScript inside the Node.js environment with the help of the sqlite3 Node.js driver.

Node.js Docker workflow

This article guides you through how to optimize the production artifact, normalize environments, and improve integration and delivery in a Node.js app, that Docker will bring to another level.

How to Debug Your Node.js Application on OpenShift with Chrome DevTools

This article is a step-by-step guide on how to debug and inspect your running code using the Chrome Developer Tools (DevTools) inspector.

A Word About Node.js Event Loop

If you want further clarification on how event loop works, check out this article for a better understanding.

Weekly Node.js Update - #20 - 05.18, 2018

Previously Node.js Updates:

In the previous Weekly Node.js Update, we collected great articles, like

  • Node v10.1.0 (Current) is released;
  • Node.js Foundation Executive Director’s Update, May 2018;
  • Golang vs Node.js;
  • Working with stdout and stdin of a child process in Node.js;

& more…

We help you to stay up-to-date with Node.js on a daily basis too. Check out our Node.js news page and its Twitter feed!

Source:: risingstack.com