Joseph Jude

Consult . Code . Coach

Getting started with HapiJS and Typescript


code . nodejs . hapijs . tsc

Is it possible to use Typescript as a full-stack language? That's the experiment, I want to run. Use angular2 as a UI framework, ionic as a mobile app framework, hapijs as a server app framework, and electron as a desktop app developing framework. Wouldn't that be fun?

So here is the first in a, hopefully, a long series.

Hapi is a product of Walmart labs. With hapi, they managed the load during black friday sale without a crash. If you are learning a nodejs framework, why not learn the best?

Since hapi is a node framework, it goes without saying that you need to install node and npm. If you don't have node installed, install it using a package manager.

Since we are starting with node & npm, use node best practices, especially Use a smart .npmrc. These configurations lock the versions of the dependencies. So when you migrate your app from development to testing and to production, you will use the same versions of your dependencies.

npm config set save=true
npm config set save-exact=true

Let us get on with hapi.

Create a hapijs project

mkdir helloworld && cd helloworld
npm init

npm init will ask series of questions to configure your app. It will automatically create a package.json from your answers. pacakge.json is required to run node programs.

Now let us install hapi.

npm install hapi

We are not using --save because using the npm config, we have already indicated that we always want to save whatever we install.

After that, create a new file index.js and copy this code.

const hapi = require('hapi');

const server = new hapi.Server();
server.connection({port: 3000});

server.start((err) => {
if (err) {
    throw err;
}
console.log('Server running at:', server.info.uri);
});

This is copy of the first tutorial from Hapi site. Run it with node .. This will run the server at port 3000. However, if you open your browser to http://localhost:3000, you will see an error, {"statusCode":404,"error":"Not Found"}. That is because, this little program doesn't know how to handle the incoming requests.

Let us create a function so that the app displays "Hello World". The modified program looks like this.

const hapi = require('hapi');

const server = new hapi.Server();
server.connection({port: 3000});

// new codeblock
server.route({
    method: 'GET',
    path: '/',
    handler: function (request, reply) {
        reply('Hello, world!');
    }
});

server.start((err) => {
    if (err) {
        throw err;
    }
    console.log('Server running at:', server.info.uri);
});

Add Typescript support

Now let us add Typescript support for Hapi. For that, we need to have Typescript installed. Install Typescript with the below command:

npm install -g typescript

To use Typescript with existing JavaScript frameworks, we need to install Type definitions for Hapi. Think of type definitions as bridge between Typescript and HapiJs written in JavaScript.

npm install typings --global

You can now search for a type definition for Hapi, using typings search hapi. You can install the type definition with typings install dt~hapi --global --save. You have to install typings for node too. You can do so with this command: typings install dt~node --global --save.

Convert to typescript

Now we can re-write our program in typescript (If you are looking for a reference guide for Typescript, I wrote one earlier). Here is the modified program. Name the program file as index.ts.

 /// <reference path="./typings/index.d.ts" />

"use strict";

import * as hapi from "hapi";

const server: hapi.Server = new hapi.Server()
server.connection({ port: 3000 });

server.route({
    method: "GET",
    path: "/",
    handler: (request: hapi.Request, reply: hapi.IReply) => {
        reply("Hello World")
    }

});

server.start((err) => {
    if (err) {
        throw err;
    }
    console.log("server running at 3000");
})

Execute

Since the program is in typescript, we need to compile the program into JavaScript so that node can run it. We do that with tsc index.ts. This will compile and generate index.js file. Then you can run the program like before with node .. If you open the browser and point it to http://localhost:3000, you can see a Hello World message.

This is only a start. More to come.


Like the post? Retweet it. Got comments? Reply.

Getting started with #hapijs and #typescript by @jjude https://t.co/sqATAaOxQN

— Joseph Jude (@jjude) September 26, 2016
Share this on: Twitter / /

Comments

comments powered by Disqus