Chapter 1. Introducing hapi.js

hapi.js (commonly referred to as hapi) stands for HTTP API. It is a rich framework for building applications and services. It was originally designed for the rapid development of RESTful API services using JavaScript, but has since grown to be a full web application framework with out-of-the-box features for templating, input validation, authentication, caching, and more recently, support for real-time applications with web socket support.

The original philosophy that hapi was built around was increasing developer hapi-ness; the aim was to increase productivity by providing additional tools to help with development, but without getting in the way. It was also built with a security-first approach, meaning that the tools provided were developed with smart secure defaults, with the mindset of not giving the developers the ability to shoot themselves in the foot for not knowing some hidden configuration setting or implied design pattern.

hapi was created by the Mobile team at Walmart Labs, led by Eran Hammer (who created OAuth), to handle their traffic for events like Black Friday, one of the busiest days for online shopping in the US calendar.

hapi was born out of necessity; the Walmart team never intended to build a framework. They originally started with express, currently Node's most widely used framework. After hitting some limitations with express, and finding similar limitations in other frameworks, they finally discovered that it would be easier to create their own framework rather than hack an existing framework to meet their needs. Eran wrote a great post about this journey on his blog, http://hueniverse.com/2012/12/20/hapi-a-prologue; I encourage you to read it. Fortunately for us, hapi was born out of all this.

This chapter will be your introduction to hapi.js, and will cover the following topics:

  • Introducing Node.js—a prerequisite to learning hapi.js
  • A background on hapi.js
  • Creating our first hapi.js server

Node.js – a prerequisite to learning hapi.js

As this book is aimed at JavaScript developers, who may or may not have prior experience with Node.js (https://nodejs.org/), I would like to first introduce Node.js. Node.js (commonly referred to as Node) is a platform built on Chrome's JavaScript runtime called V8 for easily building fast and scalable web applications in JavaScript. To put it succinctly: server-side JavaScript.

The thought of server-side JavaScript might seem strange to those unfamiliar with the concept, but it has some big advantages over other server-side technologies such as PHP, Java, Ruby, and many others. For one, V8, on which Node is based, is fast, and has a full-time team in Google constantly improving its performance with each release of Chrome. One of Node's biggest differentiators as compared to other server-side technologies is its single-thread nature, encouraging the asynchronous coding style that you may be familiar with from working with JavaScript on the client side. Among its asynchronous nature, Node.js has many advantages, some of which are as follows:

  • Reduces the need for multi-threading, always considered a tough problem in application development
  • Allows sharing of code between browser and server, and avoiding a context switch between working with the browser and client
  • It comes bundled with npm, currently the biggest package manager and one of the best solutions out there for managing your application dependencies on both client and server seriously, you will struggle to move back from Node after having the luxury of such an excellent resource

As a result of these and many other benefits of Node, many large organizations such as Netflix, Yahoo, Mozilla, PayPal, and of course the organization behind hapi.js, Walmart, have adopted Node. If you aren't familiar with Node or npm, I suggest you take some time to read up on them at https://nodejs.org/about, https://docs.npmjs.com. The Node.js website covers the installation of Node, and I suggest you do this so you can participate in this next part.

Let's take a look at what a simple' hello world' API server looks like in Node.js by using the example from the Node.js website (please take note that you need Node version 4 or greater to run this code, otherwise you will get syntax errors!):

const http = require('http');                           // [1]
const hostname = '127.0.0.1';
const port = 1337;
http.createServer((req, res) => {                       // [2]
  res.writeHead(200, { 'Content-Type': 'text/plain' }); // [3]
  res.end('Hello World
');                             // [4]
}).listen(port, hostname, () => {                       // [5]
  console.log(`Server running at http://${hostname}:${port}/`);
});

Tip

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

  • Log in or register to our website using your e-mail address and password.
  • Hover the mouse pointer on the SUPPORT tab at the top.
  • Click on Code Downloads & Errata.
  • Enter the name of the book in the Search box.
  • Select the book for which you're looking to download the code files.
  • Choose from the drop-down menu where you purchased this book from.
  • Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR / 7-Zip for Windows
  • Zipeg / iZip / UnRarX for Mac
  • 7-Zip / PeaZip for Linux

I won't cover what happens here in detail, but will skim over the need to know parts to help understand how a typical Node server operates. With reference to the numbers in the code comments, let's go through each line:

  • [1]: This is an example of using modules in Node.js. While many modules need to be downloaded using npm install, some modules like http are bundled with the Node binaries. In this example, we require the http module and assign it to the variable http. This is where we first see the ES6 syntax being introduced through the const keyword. Here, const basically specifies that we cannot redefine the http variable. If you want to read more about how Node modules work, you can find a good explanation in the Node API documentation at https://nodejs.org/api/modules.html.
  • [2]: Here, we use the createServer method of the http module. We pass a callback function as an argument, which will then be called every time the server receives a request. This is the second example of the ES6 syntax being introduced, which is the arrow function. I suggest you read up on its differences with a normal function call at https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions. The callback function then takes two parameters: req, which contains information about the request that the server has received, and res, which is an object that contains the methods for responding to a request.
  • [3]: Here we see the low level to which the Node http module goes, where you must set response headers and status codes; this is done by calling res.writeHead().
  • [4]: The line res.end() signals to the server that all of the response headers and body have been sent, and the server should consider this request complete.
  • [5]: Now that we have a server defined, we must tell it to accept connections for a particular port and hostname, and this is done by the server.listen() method.

That was a lot of information at once, so don't worry if it didn't make sense immediately; the concepts introduced here will become clearer as we talk more about them throughout this book.

To run this example, you should have Node installed. As I mentioned previously, instructions can be found on the Node.js website. Next, you need to create a folder and change to its directory:

$ mkdir hello-node && cd hello-node

Then create a file called hello-node.js, paste it in the preceding code and run it using the following command:

$ node hello-node.js

If all goes well, you will see the following screen:

Node.js – a prerequisite to learning hapi.js

Looking back at the preceding example, think now, how would you add functionality to this server while keeping your code base manageable? It certainly is not trivial. Especially when taking into account that typical servers will want to be able to serve static content as well as plaintext, JSON, XML and many other types. Often, it would need to deal with different request URLs and respond accordingly. Generally, it would need to interact with some type of persistent data store such as MySQL, and we still haven't even thought about authentication, authorization, validation of requests, and a number of other features that a typical application would need. This is what we refer to as application infrastructure, and this is where hapi.js comes in.

hapi is, in one sense, an abstraction layer on top of this low-level server, for providing more intuitive APIs for solving the previously mentioned problems, so you don't need to. It is a rich framework that allows you, the developer, to focus on writing reusable application logic instead of spending time building infrastructure.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.170.63