hapi - GradedJestRisk/js-training GitHub Wiki
List:
- Manning Hapi.js in action (2017 - hapi13) code
- install
npm install @hapi/hapi
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"}%
List:
- incoming: onRequest
- outcoming: onPreResponse
See also pre configuration
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')
On:
- URL: /foo/8
validate: { params : {} } - query:
validate: { query : {} } - payload:
validate: { payload : {} }
4xx errors mapping You can pass arguments fro hapi to make an detailed response, sample here
Implemented here
List:
- display route table on startup: blipp
- add healthckeck route: hapijs-alive
- send error to Sentry: hapi-sentry
- monitor:
- hapijs-status-monitor to display server metrics on web application
-
good (deprecated), combined with
- good-squeeze to filter events
- good-console to output to console
- laabr, an enhancement (eg. color) over hapi-pino
Each plugin can subscribe to hapi events, eg:
- request
- request-error
- response
- uncaught
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