ES6 Spread/Rest Operator

ES6 has a handy feature called the Spread/Rest operator notated as .... The reason is has two names is because based on the use, it can do two different things.

Spread

For example, we can spread an array of values into a function parameters.

function myFunction(a, b, c) {
   console.log(a, b, c)
}

myFunction(...[1, 2, 3]) // outputs 1, 2, 3

We can aslo spread one array into another to improve array concatenation like so:

const a = [1, 2];
const b = [3, 4]'
const c = [...a, ...b];

console.log(c); // Results in [1, 2, 3, 4]

Rest

You can also use the operator to gather items into an array. A common usage of this is accepting extra arguments into a function

function myFunction(one, ...args) {
    console.log(args);
}

myFunction(1, 2, 3); // prints 1, [2, 3]

For more info, check the MDN docs

Quick start with Sails.js – Opinionated Javascript

While Node.Js has done create with unopionated frameworks that allow for conversation and new trials, sometimes you need some direction. During my development time I’ve seen the benefits to using something like Rails or Laravel with best practices built in. Of course, they come with a lot of bloat you may not need. However, if you are looking for some great practices and most features bootstrap, NodeJs can now deliver with Sail.js.

Here is a quick guide to getting set up. Navigate to your terminal and install the Sails command line tool.

npm install sails -g

Then, create a new project.

sails new sails-project

You will have to option to start and empty project (allowing for more configuration) or start with a full template. Let’s choose option 1 (full app).

Now, let’s boot up.

cd new-project
sails lift

Now visit http://localhost:1337/ and you will be set!

Check out the official docs to learn more.

Creating Your First Slack Bot in Nodejs

If you are looking for a good introduction to the world of AI or are simply wanting to be trendy and cool, Chat Bots are the answer. In this post, I’ll get you started with a quick chat bot in Nodejs.

Getting Permissions

First, we will need to let Slack know about our bot and grab an API key.

  1. Go to this URL: https://my.slack.com/services/new/bot
  2. Enter a username for your bot. We will call this one, testbotScreen Shot 2018-04-14 at 12.05.38 AM.png
  3. Scroll down to Integration Settings and grab the API key. I’ve deleted the one below 😛Screen Shot 2018-04-14 at 12.07.52 AM.png

Creating the Nodejs Bot

Alright, now that we have our creds, let’s create a bot.

First, create a new directory, initialize a project and install the slackbots library.

mkdir my-first-bot
cd my-first-bot
npm init -y
npm install slackbots --save
touch index.js

Alright! So now, let’s initialize the bot using the API key from above. In the ​index.js add the following.

const SlackBot = require('slackbots');
const bot = new SlackBot({
    token: 'xoxb-346962835285-DOgbKAsXuvn5tTYOrlUOyJYB', 
    name: 'My Bot'
});

Sweet, now let’s create an on start message to let everyone know we are connected.

bot.on('start', () => {
    bot.postMessageToChannel('general', 'Hello!');
});

The above will post a hello message in the general channel when the bot has connected. One last thing we shoul do for this tutorial is respond to users. Let’s start by adding the on message event.

bot.on('message'(data) => {
    console.log(data);
});
Next, we will check if the user is messaging our bot and then reply to them if so.
bot.on('message'(data) => {
    if (msg.username === 'My Bot') {
       bot.postMessage(data.channel, 'Yo!);
    }
});
The above checks if the username of the message is to our bot and sends a reply to the user in the same channel.
And that’s all for this tutorial! I’ve been making quite a few bots lately, so I’ll be posting more about how to create bots and the different feature you can use. Let me know if you have any questions.

Project Best Practices: Adding Integration Tests

In this tutorial, we will get you set up running integration tests with ExpressJS. While I will be using a specific library, you can generalize these methods to meet the app you are using.

Integration tests will differ from Unit tests in the sense that they treat the app as a block box. For us, we will be testing our API which means sending API calls and checking the returns.

Set Up

Run the following commands to get a clean project

mkdir test-integrations
cd test-integrations
npm init -y
touch index.js
mkdir test

Initial Api

Now, create our basic API with one route

npm install express --save

Then in the index.js file

const express = require('express')
const app = express()

app.get('/hello-world', (req, res) => {
  return res.status(200).send({msg: 'Hello World!'})
})

app.listen(3000, () => console.log('Example app listening on port 3000!'))

module.exports = app;

This is basically the hello world example form ExpressJS’s site, but I’ve change the return value to JSON so we can test it as if we were working on a real world API.

Creating our test

Let’s start by installing our test libraries.

npm install mocha chai chai-http --save
  • We will be using chai to do assertions. For example. expect(1 === 1).to.eql(true)
  • We will use chai-http to make requests to our API
  • And finally, we will use mocha to run our test and organize them

All of this will make more sense with an example 🙂

Let’s create a file in our test directory. You can name your file how you’d like, but this is my preferred format.

touch test/GET-hello-world.test.js

In the above file, let’s add the following to the top of the file

// Testing Libraries
const chai = require('chai');
const chaiHttp = require('chai-http');

// Api
const server = require('../index');

// Global to help with code style
const expect = chai.expect
chai.use(chaiHttp);

This will import our testing libraries and our api. We also tell chai to use the http module and create a global expect variable to keep our tests concise.

Now, add the first test

describe('/GET Triggers', () => {
  it('returns hello world', async () => {
    const response = await chai.request(server).get('/hello-world');

    expect(response.status).to.eql(200);
    expect(response.body.msg).to.eql('Hello World!');
  });
});

Here we use a function called describe which simply organizes our tests into a group. You will see this in the output after we run the test. You can also declare describe sections inside other describes.

The second function is the it function which defines a specific test. You can see here that we use chai to call a request to our server. Afterword we use the expect global variable to assert our status and body on the response.

Create an error test

Let’s also create an error test so you can see how that work. We will call an api route that does not exists and check that express returns a 404.

Inside of the describe function add the following

it('errors route is not found', async () => {
  try {
    await chai.request(server).get('/fake-url');
  } catch (e) {
    expect(e.response.status).to.eql(404);
  }
});

Conclusion

Here is the final result of our code

// Testing Libraries
const chai = require('chai');
const chaiHttp = require('chai-http');

// Api
const server = require('../index');

// Global to help with code style
const expect = chai.expect
chai.use(chaiHttp);

describe('/GET Triggers', () => {
  it('returns hello world', async () => {
    const response = await chai.request(server).get('/hello-world');

    expect(response.status).to.eql(200);
    expect(response.body.msg).to.eql('Hello World!');
  });

  it('errors route is not found', async () => {
    try {
      await chai.request(server).get('/fake-url');
    } catch (e) {
      expect(e.response.status).to.eql(404);
    }
  });
});

As you can see, it is easy to get started! Basically you call a request to your api routes, then check the output. There is much more detail we can get into, but we shall cover that in later lessons.

Project Best Practices: Setting Up ESLint

This is part of a series about NodeJs best practices for your projects. Every project you build will become more maintainable with these practices. They are not everything (we will get there), but they are more than a good start.

This tutorial goes over setting up ESLint. You can check out the official docs right here: https://eslint.org/docs/user-guide/getting-started. The docs are pretty straightforward 😀

Let’s start by creating a new project

mkdir eslit-test
cd eslint-test
npm init -y

No we will add eslint

npm install eslint --save-dev

And initialize it by

./node_modules/.bin/eslint --init

This will ask you if you want to use a preset ESLint or answer questions about your Javascript uses. I prefer the Standard or AirBnB preset.

That’s it! Now you can run lint using the command below or by connecting a plugin to your text editor. I use Atom + the Eslint plugin

eslint yourfile.js