hapi - GradedJestRisk/js-training GitHub Wiki

General

h in code refer to hapi

List:

Hello, API

Bootstrap a server with a GET route from docs

Create a project npm init --yes

Install package npm install @hapi/hapi

Create index.js

const Hapi = require('@hapi/hapi');

const init = async () => {

    const server = Hapi.server({
        port: 3000,
        host: 'localhost'
    });

    server.route({
        method: 'GET',
        path: '/',
        handler: (request, h) => {

            return 'Hello World!';
        }
    });

    server.events.on('response',  (request) =>{
        console.log(request.info.remoteAddress + ': ' + request.method.toUpperCase() + ' ' + request.path + ' --> ' + request.response.statusCode);
    });

    await server.start();
    console.log('Server running on %s', server.info.uri);
};

process.on('unhandledRejection', (err) => {

    console.log(err);
    process.exit(1);
});

init();

Start the server npm start

Send a request curl localhost:3000

Hooks

List:

  • incoming: onRequest
  • outcoming: onPreResponse

Full list here

See also pre configuration

Authentication

To enable access with both authenticated and unauthenticated user.

Step 1 - use mode: 'optional'

{
  config: {
    auth: {
      mode: 'optional';
    }
  }
}

Step 2 - raise a custom error in your authenticator

    boom.unauthorized(null, 'unauth')

From here

Framework test here

Validation

On:

  • URL: /foo/8 validate: { params : {} }
  • query: validate: { query : {} }
  • payload: validate: { payload : {} }

Routes

Handle

Test

Exception

boom.js

4xx errors mapping

You can pass arguments fro hapi to make an detailed response

Sample here

plugins

Implemented here

List:

monitoring

request

Each plugin can subscribe to hapi events, eg:

  • request
  • request-error
  • response
  • uncaught

Event list:

server health

Server usage events (ops) are not emitted by hapi, but oppsy(deprecated), which use basic node libraries:

There is [no suggested candidate](https://github.com/hapijs/good/issues/568], but the only available plugin is hapi-k8s-health based on prometheus.

A bare client for node is prom-client

⚠️ **GitHub.com Fallback** ⚠️