hapi - GradedJestRisk/js-training GitHub Wiki
h in code refer to hapi
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
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
List:
- incoming: onRequest
- outcoming: onPreResponse
Full list here
See also pre configuration
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')On:
- URL: /foo/8
validate: { params : {} } - query:
validate: { query : {} } - payload:
validate: { payload : {} }
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:
- display server metrics on web application : hapijs-status-monitor
- an enhancement (eg. color) over hapi-pino : laabr
Each plugin can subscribe to hapi events, eg:
- request
- request-error
- response
- uncaught
Event list:
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