5 Most useful ES6+ Features

In this post, I am going to share with you Javascript ES6+ features that I find the most useful:

  1. For…of Loop
  2. Arrow Functions
  3. Async and Await
  4. Template literals
  5. Destructing

For…of Loop

Before either we had to write a full for loop or call the forEach function on the array to iterate over its item.

Previously we had to do this

Now with the new version of JavaScript, we can simply write the For…Of loop

If we have to iterate over an object’s keys we can use the For…In loop

Arrow Functions

If you have done programming in JavaScript you must be familiar that we have to create a LOT of functions in javascript as it is an asynchronous programming language.

With the new Arrow Functions, it makes the code cleaner and also saves you a few keystrokes.

Consider the following example, previously we had to do this

Now with the ES6+ syntax, it can be compressed into a single line, in a single like arrow function we don’t have to write the return statement, the value of whatever expression preceding the arrow will be returned.

We can also create multi-line arrow functions that accept multiple arguments

Async and Await

This is the feature that I use a lot especially when doing server-side programming using Node.JS, but you can also use it on the front-end and it also works in all the major browsers.

With Async and Await keywords, you can write asynchronous code that uses promises appear as if it is synchronous and make the code more readable.

Consider the following example without async await

Now with Async and Await keywords, we can update the code and make the asynchronous functions look like synchronous functions and it results in a much cleaner code, see for yourself:

As you can see with the update the code is much more simplified. To use async-await first you have to create a function with keyword async, then inside the function, you can call asynchronous methods that uses promise and add the await keyword in front of the function call.

Template literals

Template literals is a very useful feature, previously we had to use string concatenation the can quickly get out of hand if we are using multiple values or if want to construct a multi-line string, consider the following example

The code can be simplified with template literals

To use the template literal we have to enclose the string in ` and then enclose the variable name under ${<variable_name>}

Template literals can also expand to multiple lines

Imagine constructing the above code using string concatenation, it would be an unreadable mess.

Destructuring

Destructuring allows us to extract values from an object and easily assign it to variables.

Considering the following example, here is what we normally do when we want to extract values from an object

With destructuring you can simplify the code as following:

and we can use the name, age, and occupation as variables in our code.

That’s it!

These the feature that I find the most useful in ES6+, please share if you found it interesting and let me know in the comments what ES6+ feature you like the best.

 

Embedding Rocket Chat using iFrame Auth

Recently I was working on a project where I had to embed Rocket.chat on a website, and when the user login to the website, they will also get automatically logged-into Rocket.chat

The following steps have to be performed:

  1. Check if the user exists in Rocket.chat
  2. If the user exists then login user
  3. If the user doesn’t exist then create the user in Rocket. chat and log in the user

I went through the Rocket chat documentation and figured out the best way to do it would be through a combination of iFrame Auth and the Rocket chat REST API. The iFrame Auth will be used to perform login and Rocket chat REST API to create a new user and generate tokens, but the documentation regarding the iFrame Auth was not quite clear and it was confusing, I also studied the provided example code and then after some fiddling I was able to implement my solution and I will walk you through the steps:

Login, Create Account and Server Setup

When doing iFrame Auth, Rocket chat sends few requests to our server so we will have to create few API’s on our server that Rocket chat server would call to authenticate the user.  I am using Node.JS + Express on the server side in the following example:

Creating a wrapper to encapsulate Rocket chat API

We will call the Rocket Chat API to create a user in Rocket chat and we will also use it to Login the user and get the token.

First, we will have to obtain Rocket Chat Admin UserID and Admin Auth Token, this can be done by simply calling the Rocket Chat Login API:

 

Here http://localhost:3000 is the Rocket Chat URL and in place of myusername enter your Rocket chat admin username and under mypassword enter your password.

You’ll get a response something like this

 

Extract authToken and userId from the above response as we would need it in the next step.

Now we have to authToken and userId of the Rocket chat admin, we can use this to call Rocket Chat API and create new users in Rocket Chat.

The above code snippet we have created a few methods that are very self-descriptive. We will use these methods to create and login user into the Rocket Chat when user login to our server.

Creating API’s

In the above code snippet, we are creating routes that Rocket Chat will call to fetch the login token and authenticate the user, in the next step we will update the Rocket Chat Setting and include these routes.

Setting up Rocket Chat

There are few configurations that we have to make in Rocket chat to get it working with iFrame Auth.

Step 1:

Go under Accounts->iFrame and update the settings as per the screen-shot below Here we are specifying the routes that we had created in the previous step. http://localhost:8080 is where our local Node.JS server is running.

Step 2:

Go under General->iFrame Integration and update the settings as per the screenshot 

Embedding Rocket Chat

Now, after the setting on Rocket chat is done, we will embed Rocket chat into our web page, now embedding Rocket Chat is as simple as adding the iFrame on the page you want to embed

See the example below

Here http://localhost:3000 is the address of the Rocket Chat server and adding ?layout=embedded shows are cleaner UI.

Conclusion

That’s’ it! Let me know if you have any questions or suggestions in the comments below.

 

 

How to setup multi-domain SSL in Node.JS using letsencrypt-express/greenlock-express

Updated (22/June/2018): Support for Let’s Encrypt v2

I have updated the code snippet below to include the support for Let’s Encrypt v2 in the snippet below:

 

I wanted to set-up a multi-domain SSL certificate using LetsEncrypt for my app “Dead Simple Screen Sharing” because people complained about the long meeting URL, so I bought a short domain mnow.io and edited the code to generate short 6 digit meeting ids, so the new meeting URL became much cleaner e.g https://mnow.io/345686 instead of the original https://app.deadsimplescreensharing.com/meeting/bgasGca-1

But I needed a new SSL certificate for the domain mnow.io, and as this domain will also be pointed to the same server, I required a multi-domain SSL certificate.

I had already configured greenlock-express (letsencrypt-express is now called as greenlock-express) on my server so just had to make some changes in the configuration and add my domain, but simply adding the domain in the domains array didn’t work, so after some trial and error I finally figured it out.

Here is the final code snippet, that you can use, add this in your app.js or server.js:

 

In line 10 replace ‘domain1.com’ and ‘domain2.com’ with your own domains, if you have more than 2 domains you can add them in the array, if you have only one domain then you also keep just one single domain in the array.

In line 12 replace ‘[email protected]’ with your email address.

The code on line 19 to 23 is optional, you can add it if you want to redirect all your traffic to https, and if you skip it then both HTTP and HTTPS versions of your site will be live.

Let me know if you have any questions, concerns or suggestions in the comments.

 

Using Postgres with Parse Backend

Facebook killed parse last year, but thankfully they Open-Source the parse backend. Initially, the Parse Backend only supported MongoDB database, but later support for  Postgres has been added by the contributor from the community.

So using Postgres with Parse Backend is really quite simple, you just have to install the latest version of Parse Backend, and in the databaseURI specify the Postgres connection string.

Here is an example:


 

As you can see in the example above we have specified the connection string to connect to the Postgres database.

If you are not familiar with the structure of the connection string, then here is the breakdown.

If you have any question, please leave the comment below.

 

Introduction to SalisJS

I was looking for a Node.JS web framework for my project, and in my quest for finding the best framework, I stumbled across Sails.JS, and I have been using it for a few months now and it is pretty awesome at most of the part, so if you need something like Rails for Node.js, Sails is the way to go.

The Sails.JS is an MVC framework, so there are Models, Views and Controllers.

Models:

In Sails.JS you can create models, and model represents the data model, so if for each table you would have a model and in case of no-sql databases, each collection is represented by a model.
Inside a model you can describe, the attributes present in that model, their datatype and validation rules.

Example of a User Model:
user.js

In the above example we have a user model, which has a number of attributes, like firstName, lastName, email and role.
The model structure is pretty straightforward, and Sails.js provides some useful helpers in modules like the enum.
We have added an enum attribute in role, now Sails will accept only the values present in the enum array.

Magic:

The magical part is sails is blueprints. Sails will create CRUD routes based on the data model.
Sails will look at your data-model and will create blueprint routes and REST api.
So, by looking at the model we have created above sails will create REST APIs.
Create User: HTTP POST: /user
Update User: HTTP PUT: /user/:id
Delete User: HTTP DELETE: /user/:id
Fetch User: HTTP GET: /user/:id
Get All Users: HTTP GET: /user

Associations in Model

In Sails you can associate one model with another model, and associations can span across databases.
So if you have user data stored in Postgres and photos stored in Mongodb, you can interact with the data if they lived in the same database.

Many to Many

In this type of association, one model can be associated with many other models and vice versa.
Lets consider an example of a Real Estate, a Real Estate can be owned by multiple people, a person can own multiple Real Estates.
Thus we can create a many to many relationship between people and real-estate.
So, let’s begin:

So, in the above example we have created two models, one is user model and another one is estate model.

In the estate model we have created a property named owner, which reference the user model model and points to the owners of the property, so this will be an array containing all the owners of the property.

In the User model we have created a property named estates, and it points to the estate model and it will contain all the estates owned by the user.

LifeCycle callbacks in Models

There are lifecycle call-backs present in the models which are very helpful, for e.g: If want to can write some cleanup code when an item in a model is deleted, so you can write the code for that inside the afterDestroy method.

Callbacks on create

Callbacks on update

Callbacks on destroy

Consider the example:

To learn more about the lifecycle callbacks, see the official documentation.

Controllers

The main logic of your application will be present in the controllers, the controllers are responsible for responding to the requests.
Although, some magic is provided by Sails, using blueprints to create automatic CRUD API, often times it is not enough and you will want to add more functionality and more types of routes.

Consider an example controller file name greeting.js:

The above file contains two actions, namely hello and hi, inside these actions we can write the code to do whatever we want, in the above example we are sending messages, “hello world” and “hi user” respectively.

Sails has automatic routing, so the controllers and actions that you have created will be routed automatically, by the following format /:controller/:nameOfAction.

So routes for our above actions will be /greeting/hello and /greeting/hi.

Overriding blueprint actions

If you want override the blueprint actions, like create, update or delete, just create actions in the controller with that name and it will override the default functionality.
Suppose we want override the create functionality for user, so in user controller, we will create an action having the name create.

The above code overrides the create functionally, now if we send a http post request at url /user, instead of creating a new user it will send a response “Hello world”.

In the similar manner we can override the default behaviour by creating actions having the name create, update and delete.

Policies

You don’t want anyone accessing and performing unintended activity, like deleting all your real estates, so for that we have policies.
If you are familiar with ExpressJS, polices are similar to ExpressJS middle-wares.
The official SailsJS documentation explains policies in great detail, be sure to head over there and read about it in details.

Conclusion

That’s my take on SailsJS, it’s a great framework to build apps in Node.JS.
Let me know if you have any suggestions, questions about this in the comments.

Building command line apps in Node.js

Node.js is becoming very popular platform for creating command line utilities, so I am writing this blog post to help you get started.

Creating an executable script

To create an executable script you will have to add shebang at the top of the script. E.g:

Assuming you are on a UNIX like system, you will also have to change the permission of the script and make it executable.

and now you can execute the script:

Accepting arguments

You would also want use command line tool to accept arguments, which you can do using process.argv. This is an array which will contain all the supplied command line arguments.

script.js

The above script will print out all the supplied arguments, when executed it will generate the following out:

To remove ‘node’ and path from your script can slice out those arguments:

There several libraries out there that will make the task of accepting arguments easier, but if you are doing something trivial, I would suggest sticking to the default method.
One notable example of such library is cli.

Colors on the command line

If you want to display messages with different colours, there is a nice library called as colors to do it effortlessly.
Install it via nom:

And then include it in your script:

Exit event

If you want to preform some operation on exit, you can listen to the exit event. Once the exit event is called there is no way to prevent the exiting of the event loop, hence you must only perform synchronous operations in this handler.

Exit codes

Node.js provides supports for exit codes, if you script exits without any error, the exit code should be 0. If your script exits with an error it should be 1 or higher.
Exit codes in node.js are passed using process.exit().

Process object

process.uptime()
Returns the number of seconds the script has been running

process.memoryUsage()
Returns an object describing the memory usage

process.pid
The PID of the process

If you have any questions or suggestions feel free to comment.

Executing tasks (functions) on specific dates in Node.js

Sometimes you want to execute task after certain interval, I am not talking about executing a task after every 5 minutes, but after certain days; say every Monday at 5pm more like corn jobs.

If you are looking for a library which allows you to execute arbitrary functions at specific dates, so you’re in luck because an awesome Node.js library called node-schedule allows you do just that.

Head over to Github repo, and read about it in detail and get started.

PeerJS How does it work?

I was very excited about the latest Web RTC API’s on Peer-To-Peer video calling and file transfer, and when I reading about these new API’s I came accorss a awesome javascirpt plugin PeerJS, which allows to use the p2p data transfer easily.

I decided to use it for my screensharing app deadsimplescreensharing, becuase I am hosting the server on heroku and I am facing huge latency issues and I thought using peer-2-peer would be perfect to solve my problem, but sadly it didn’t work!

The Problem:

I modified my screensharing app’s chrome extension to work with peerJS and also the client webpage.
Then I launched the localserver to test it, I got a connection with the extension I could see data being transmitted from the extension but not being recived at the client side.

I then tried to send small messages like “Hello”, “Hi” etc. and I was able to recive them at the client just fine, so I figure out the problem was peerJS was unable to send large files (around 700 KB), and that part totally sucks!

The Solution:

The possible soloution I could think about is converting the data:uri (screensharing fetch’s the current tab image using data:uri) into an array and then dividing the array into smaller chunks and send them.
At the client side, recieve the chunks, join and assemble them and then display the image.

Here is the code which I used:

The above code divides a large array into smaller arrays of size 1000 each which can be transmitter over the network.

Conclusion

There is still lot of work that needs to be done in p2p file transfer or there is some serious issue with peerJS, as it cannot send large files and if it could the file transfer speed is very slow.
Still the thought of p2p connection is exiciting and I am wating for this new technology to develope so that we all can build cool applications using it