hapi - GradedJestRisk/js-training GitHub Wiki

Table of Contents

General

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

use strict';

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

Send a request you>should get <code>{"statusCode":404,"error":"Not Found","message":"Not Found"}%

Hooks

List:

  • incoming: onRequest
  • outcoming: onPreResponse
Full list here

See also pre configuration

Authentication

To enable access with authenticated and no authenticated 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: - short - full

server health

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

There is [no], but the only available plugin is hapi-k8s-health based on prometheus. A bare client for node is prom-client

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