### Create Basic hapi Server Source: https://hapi.dev/tutorials/gettingstarted_lang=en_US Initializes a new hapi server listening on a specified port and host. This code requires the '@hapi/hapi' package and sets up basic error handling. It's suitable for starting any hapi project. ```javascript 'use strict'; const Hapi = require('@hapi/hapi'); const init = async () => { const server = Hapi.server({ port: 3000, host: 'localhost' }); await server.start(); console.log('Server running on %s', server.info.uri); }; process.on('unhandledRejection', (err) => { console.log(err); process.exit(1); }); init(); ``` -------------------------------- ### Add 'Hello World!' Route to hapi Server Source: https://hapi.dev/tutorials/gettingstarted_lang=en_US Adds a GET route to a hapi server that responds with 'Hello World!'. This builds upon the basic server setup by defining the path and handler for a specific endpoint. It demonstrates how to handle incoming requests and return a simple response. ```javascript '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!'; } }); await server.start(); console.log('Server running on %s', server.info.uri); }; process.on('unhandledRejection', (err) => { console.log(err); process.exit(1); }); init(); ``` -------------------------------- ### Basic Hapi.js Server Setup with Vision Source: https://hapi.dev/family/vision Illustrates the basic setup of a Hapi.js server and the registration of the @hapi/vision plugin. This code snippet initializes a server and starts it, making Vision available for use. ```javascript const Hapi = require('@hapi/hapi'); const Vision = require('@hapi/vision'); const server = Hapi.Server({ port: 3000 }); const provision = async () => { await server.register(Vision); await server.start(); console.log('Server running at:', server.info.uri); }; provision(); ``` -------------------------------- ### Example: Basic Route with Top-Level Handler Source: https://hapi.dev/api_v=16.8.4 Demonstrates how to define a simple GET route '/status' with a handler function defined at the top level of the script. ```APIDOC ## GET /status ### Description Returns a 'ok' status response. ### Method GET ### Endpoint /status ### Handler ```javascript const status = function (request, reply) { return reply('ok'); }; ``` ### Route Definition ```javascript server.route({ method: 'GET', path: '/status', handler: status }); ``` ``` -------------------------------- ### Server Initialization and Options Source: https://hapi.dev/api_v=19.2.1 Demonstrates how to create a Hapi server instance and provides an overview of the server options. ```APIDOC ## Server Initialization ### Description Creates a new server object, which acts as the main application container managing incoming requests and framework facilities. Each server typically supports a single connection. ### Method `server([options])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const Hapi = require('@commercial/hapi'); const server = Hapi.server({ load: { sampleInterval: 1000 } }); ``` ### Response #### Success Response (200) N/A (This is a constructor) #### Response Example N/A ## Server Options ### Description Controls the behavior of the server object. The options object is deeply cloned (with the exception of `listener`), and should not contain values unsafe for deep copying. All options are optional. ### Method `server.options` ### Endpoint N/A (Server options are configured during server creation or accessed via `server.options`) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Server Options Details: #### `server.options.address` - **Type**: `string` - **Default value**: `'0.0.0.0'` - **Description**: Sets the hostname or IP address the server will listen on. Defaults to `host` if present, otherwise to all available network interfaces. Set to `'127.0.0.1'` or `'localhost'` to restrict to same-host connections. #### `server.options.app` - **Type**: `object` - **Default value**: `{}` - **Description**: Provides application-specific configuration accessible via `server.settings.app`. The framework does not interact with this object. It is meant for storing static configuration values, distinguishing it from `server.app` used for run-time state. #### `server.options.autoListen` - **Type**: `boolean` - **Default value**: `true` - **Description**: Disables automatic listener initialization. When `false`, the listener must be started manually. Cannot be `false` if `port` is set. #### `server.options.cache` - **Type**: `object` or `array` of `object` - **Default value**: `{ provider: { constructor: require('@hapi/catbox-memory'), options: { partition: 'hapi-cache' } } }` - **Description**: Sets up server-side caching providers using `catbox`. Each server includes a default cache. The configuration can define one or more cache strategies using class constructors or configuration objects with `engine` or `provider`. - **`provider`**: An object with `constructor` and optional `options` (including `partition`). - **`shared`**: `boolean` - Allows multiple users to share the same cache segment. Defaults to `false`. - **Note**: One of `engine` or `provider` is required per configuration object. #### `server.options.compression` - **Type**: `object` or `false` - **Default value**: `{ minBytes: 1024 }` - **Description**: Defines server handling of content encoding requests. If `false`, compression is disabled. - **`minBytes`**: `number` - Sets the minimum response payload size in bytes required for compression. Defaults to `1024`. ``` -------------------------------- ### Hapi Github Authentication Strategy Setup Source: https://hapi.dev/module/bell/examples Sets up a Github authentication strategy using Hapi Bell. Requires a Github application with a clientId and clientSecret. The strategy handles GET and POST requests to the '/login' path for authentication. ```javascript 'use strict'; const Bell = require('..'); const Hapi = require('@hapi/hapi'); const internals = {}; internals.start = async function () { const server = Hapi.server({ port: 8000 }); await server.register(Bell); // You will need github account for setting up an application and get a clientID and ClientSecret // This is a helpful tutorial for the whole process: https://developer.github.com/apps/building-github-apps/creating-a-github-app/ // This guide will help you set up your app and generate ID and secret. server.auth.strategy('github', 'bell', { provider: 'github', password: 'cookie_encryption_password_secure', isSecure: false, // For testing or in environments secured via other means clientId: '', clientSecret: '', location: 'https://example.com', scope: [] }); server.route({ method: ['GET', 'POST'], path: '/login', options: { auth: { strategy: 'github', mode: 'try' }, handler: function (request, h) { if (!request.auth.isAuthenticated) { return `Authentication failed due to: ${request.auth.error.message}`; } return '
' + JSON.stringify(request.auth.credentials, null, 4) + ''; } } }); await server.start(); console.log('Server started at:', server.info.uri); }; internals.start(); ``` -------------------------------- ### Plugin Registration Example Source: https://hapi.dev/api_v=16.8.4 An example of a Hapi.js plugin function that registers a GET /test route and includes required attributes. ```APIDOC ## POST /register ### Description Registers a new plugin with the Hapi server. ### Method POST ### Endpoint /register ### Parameters #### Request Body - **server** (object) - Required - The Hapi server object. - **options** (object) - Optional - Options passed to the plugin during registration. - **next** (function) - Required - Callback function to return control to the framework. - **err** (Error) - Optional - Any plugin registration error. ### Plugin Attributes - **name** (string) - Required - Unique name for the plugin. - **version** (string) - Optional - Version of the plugin. - **multiple** (boolean) - Optional - Allows multiple registrations of the same plugin. Defaults to `false`. - **dependencies** (string|array) - Optional - Plugin dependencies. - **connections** (boolean|string) - Optional - Controls plugin's ability to modify connections. Defaults to `true`. - **once** (boolean) - Optional - Registers the plugin only once per connection or server. Overrides `server.register()` `once` option. ### Request Example ```javascript const register = function (server, options, next) { server.route({ method: 'GET', path: '/test', handler: function (request, reply) { return reply('ok'); } }); return next(); }; register.attributes = { name: 'test', version: '1.0.0' }; ``` ### Alternative Attributes Example ```javascript register.attributes = { pkg: require('./package.json') }; ``` ### Success Response (200) - **message** (string) - Indicates successful plugin registration. ``` -------------------------------- ### await server.start() Source: https://hapi.dev/api_v=21.4.3 Starts the Hapi server, making it listen for incoming requests on the configured port. Handles potential errors during startup. ```APIDOC ## POST /websites/hapi_dev/start ### Description Starts the server by listening for incoming requests on the configured port (unless the connection was configured with `autoListen` set to `false`). ### Method POST ### Endpoint /websites/hapi_dev/start ### Parameters None ### Request Example ```javascript const Hapi = require('@hapi/hapi'); async function example() { const server = Hapi.server({ port: 80 }); await server.start(); console.log('Server started at: ' + server.info.uri); } ``` ### Response #### Success Response (200) - **None** - This method does not return a value directly but starts the server. Logs server start information to the console in the example. #### Error Response - **Error** - If the method fails and throws an error, the server is considered in an undefined state and should be shut down. It is recommended to abort the process or call `server.stop()` first to reset the server state before retrying. ``` -------------------------------- ### await server.start() Source: https://hapi.dev/api Starts the Hapi server, making it listen for incoming requests on the configured port. Handles potential errors during startup. ```APIDOC ## POST /websites/hapi_dev/start ### Description Starts the server by listening for incoming requests on the configured port. If the server fails to start, it's recommended to shut it down and restart. ### Method POST ### Endpoint /websites/hapi_dev/start ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json {} // Empty request body ``` ### Response #### Success Response (200) - **message** (string) - Indicates that the server has started successfully and provides the URI. #### Response Example ```json { "message": "Server started at: http://localhost:8080" } ``` #### Error Response (500) - **error** (string) - Indicates that the server failed to start. - **message** (string) - Details about the startup failure. #### Error Example ```json { "error": "Internal Server Error", "message": "Failed to start server due to port in use." } ``` ``` -------------------------------- ### GET Request Example Source: https://hapi.dev/module/wreck Demonstrates how to perform a simple GET request using Wreck. ```APIDOC ## GET / HTTP GET Request ### Description This endpoint demonstrates how to perform a simple GET request to a given URL and log the payload. ### Method GET ### Endpoint `http://example.com` (or any other URL) ### Parameters None for this basic example. ### Request Example ```javascript const Wreck = require('@hapi/wreck'); const example = async function () { const { res, payload } = await Wreck.get('http://example.com'); console.log(payload.toString()); }; try { example(); } catch (ex) { console.error(ex); } ``` ### Response #### Success Response (200) - **payload** (Buffer) - The response body as a Buffer. #### Response Example ``` // Content of the response body as a string ``` ``` -------------------------------- ### server.start() Source: https://hapi.dev/api_v=16.8.4 Starts the server connections by listening for incoming requests on the configured port of each listener. A callback can be provided to handle startup completion or errors, or a Promise can be returned. ```APIDOC ## `server.start([callback])` ### Description Starts the server connections by listening for incoming requests on the configured port of each listener (unless the connection was configured with `autoListen` set to `false`). ### Method `server.start()` ### Endpoint N/A (Method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const Hapi = require('hapi'); const Hoek = require('hoek'); const server = new Hapi.Server(); server.connection({ port: 80 }); server.start((err) => { Hoek.assert(!err, err); console.log('Server started at: ' + server.info.uri); }); ``` ### Response #### Success Response (200) N/A (Method call, success is indicated by no error in the callback or a resolved Promise) #### Response Example N/A ``` -------------------------------- ### Usage Example Source: https://hapi.dev/module/basic/api_v=7.0.2 A comprehensive example demonstrating how to install, configure, and use the basic authentication strategy within a Hapi.js server. ```APIDOC ## Hapi Basic Authentication Example ### Description This example shows how to set up a Hapi server with basic authentication using the `@hapi/basic` plugin. It includes user data, a validation function using bcrypt for password comparison, and route definitions. ### Installation ```bash npm: `npm install @hapi/basic` yarn: `yarn add @hapi/basic` ``` ### Code Example ```javascript const Bcrypt = require('bcrypt'); const Hapi = require('@hapi/hapi'); const users = { john: { username: 'john', password: '$2a$10$iqJSHD.BGr0E2IxQwYgJmeP3NvhPrXAeLSaGCj6IR/XU5QtjVu5Tm', // 'secret' name: 'John Doe', id: '2133d32a' } }; const validate = async (request, username, password, h) => { if (username === 'help') { return { response: h.redirect('https://hapijs.com/help') }; // custom response } const user = users[username]; if (!user) { return { credentials: null, isValid: false }; } const isValid = await Bcrypt.compare(password, user.password); const credentials = { id: user.id, name: user.name }; return { isValid, credentials }; }; const main = async () => { const server = Hapi.server({ port: 4000 }); await server.register(require('@hapi/basic')); server.auth.strategy('simple', 'basic', { validate }); server.auth.default('simple'); server.route({ method: 'GET', path: '/', handler: function (request, h) { return 'welcome'; } }); await server.start(); return server; }; main() .then((server) => console.log(`Server listening on ${server.info.uri}`)) .catch((err) => { console.error(err); process.exit(1); }); ``` ### Usage Notes - The `validate` function is crucial for security. Ensure strong password hashing (e.g., using `bcrypt`). - The `credentials` object returned by `validate` is available in `request.auth.credentials` for authenticated requests. - Custom responses (like redirects) can be returned directly from the `validate` function. ``` -------------------------------- ### Start hapi Server with hapi API Calls Source: https://hapi.dev/module/glue/api_v=8.0.0 This snippet demonstrates an equivalent hapi server startup using direct hapi API calls. It manually configures the server, registers plugins, and starts the server. Dependencies include '@hapi/hapi' and 'path'. The logic mirrors the Glue manifest but is expressed through explicit function calls. ```javascript 'use strict'; const Hapi = require('@hapi/hapi'); const Path = require('path'); const startServer = async function () { try { const server = Hapi.server({ cache: [{ provider: require('redis') }], port: 8000 }); const plugins = []; const registerOptions = { once: false }; let pluginPath; pluginPath = Path.join(__dirname, './awesome-plugin.js'); plugins.push({ plugin: require(pluginPath) }); plugins.push({ plugin: require('myplugin'), options:{ uglify: true } }); pluginPath = Path.join(__dirname, './ui-user'); plugins.push({ plugin: require(pluginPath) }); pluginPath = Path.join(__dirname, './ui-admin'); plugins.push({ plugin: require(pluginPath), options: { sessiontime: 500 }, routes: { prefix: '/admin' } }); await server.register(plugins, registerOptions); await server.start(); console.log('hapi days!'); } catch (err) console.error(err); process.exit(1); } }; startServer(); ``` -------------------------------- ### Running Handlebars Template Example Source: https://hapi.dev/family/vision Provides instructions to run the basic Handlebars template example included with the Vision plugin. This involves cloning the repository, installing dependencies, and executing the example script. ```bash git clone https://github.com/hapijs/vision.git && cd vision npm install node examples/handlebars ``` -------------------------------- ### Getting Hapi Server Version Source: https://hapi.dev/api_v=16.8.4 This code snippet retrieves the version number of the Hapi module installed in the project. It initializes a Hapi server and then accesses the `server.version` property to get the version string. ```javascript const Hapi = require('hapi'); const server = new Hapi.Server(); // server.version === '8.0.0' ``` -------------------------------- ### Start Hapi Server with Callback Source: https://hapi.dev/api_v=16.8.4 This code snippet demonstrates how to start a Hapi server using an asynchronous callback function. The callback handles potential startup errors and logs the server's URI upon successful startup. It requires the 'hapi' and 'hoek' modules. ```javascript const Hapi = require('hapi'); const Hoek = require('hoek'); const server = new Hapi.Server(); server.connection({ port: 80 }); server.start((err) => { Hoek.assert(!err, err); console.log('Server started at: ' + server.info.uri); }); ``` -------------------------------- ### Running Vision Examples (Shell) Source: https://hapi.dev/module/vision Shows how to clone the vision repository, install dependencies, and run specific templating engine examples like handlebars. This helps in understanding different rendering scenarios. ```shell git clone https://github.com/hapijs/vision.git && cd vision npm install node examples/handlebars ``` -------------------------------- ### Initializing Hapi Server with Application Settings Source: https://hapi.dev/api_v=16.8.4 This example shows how to initialize a Hapi server with custom application settings. The `app` property in the server configuration object is used to store custom data that can be accessed later via `server.settings.app`. ```javascript const Hapi = require('hapi'); const server = new Hapi.Server({ app: { key: 'value' } }); // server.settings.app === { key: 'value' } ``` -------------------------------- ### Initialize and Start Hapi Server for Testing (JavaScript) Source: https://hapi.dev/tutorials/testing_lang=en_US This code sets up a Hapi server instance and exports initialization and start functions. The `init` function prepares the server for testing by initializing it without starting the TCP listener, while `start` is used for running the server normally. This separation allows for testing without the overhead of a running server. ```javascript 'use strict'; const Hapi = require('@hapi/hapi'); const server = Hapi.server({ port: 3000, host: 'localhost' }); server.route({ method: 'GET', path: '/', handler: function () { return 'Hello World!'; } }); exports.init = async () => { await server.initialize(); return server; }; exports.start = async () => { await server.start(); console.log(`Server running at: ${server.info.uri}`); return server; }; process.on('unhandledRejection', (err) => { console.log(err); process.exit(1); }); ``` -------------------------------- ### Basic Usage Source: https://hapi.dev/module/wreck/api_v=17.2.0 A simple example demonstrating how to make a GET request and read the payload. ```APIDOC ## Basic Usage ```javascript const Wreck = require('@hapi/wreck'); const example = async function () { const { res, payload } = await Wreck.get('http://example.com'); console.log(payload.toString()); }; try { example(); } catch (ex) { console.error(ex); } ``` ``` -------------------------------- ### Start Hapi Server Entry Point (JavaScript) Source: https://hapi.dev/tutorials/testing_lang=en_US This code snippet serves as the main entry point for starting the Hapi server. It imports the `start` function from the server module and calls it to launch the server, making it ready to accept external HTTP traffic. This is the typical way to run the application in a production or development environment. ```javascript `use strict`; const { start } = require('lib/server'); start(); ``` -------------------------------- ### Example: Route with Handler in Config Object Source: https://hapi.dev/api_v=16.8.4 Illustrates defining a GET route '/user' where the handler and caching configuration are part of a 'config' object. ```APIDOC ## GET /user ### Description Returns user information, with caching enabled. ### Method GET ### Endpoint /user ### Configuration ```javascript const user = { cache: { expiresIn: 5000 }, handler: function (request, reply) { return reply({ name: 'John' }); } }; ``` ### Route Definition ```javascript server.route({ method: 'GET', path: '/user', config: user }); ``` ### Response Example (200) ```json { "name": "John" } ``` ``` -------------------------------- ### Static File Server Source: https://hapi.dev/module/inert/api_v=6.0.5 This example demonstrates how to set up a basic static file server using the directory handler to serve files from a 'public' directory. ```APIDOC ## GET /{param*} ### Description Serves static files from a specified directory. ### Method GET ### Endpoint `/{param*}` ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```javascript // No specific request body for this GET endpoint ``` ### Response #### Success Response (200) - **File Content** (various) - The content of the requested static file. #### Response Example ```json // Example response depends on the file being served ``` ### Code Snippet ```javascript const Path = require('path'); const Hapi = require('@hapi/hapi'); const Inert = require('@hapi/inert'); const server = new Hapi.Server({ port: 3000, routes: { files: { relativeTo: Path.join(__dirname, 'public') } } }); const provision = async () => { await server.register(Inert); server.route({ method: 'GET', path: '/{param*}', handler: { directory: { path: '.', redirectToSlash: true, index: true, } } }); await server.start(); console.log('Server running at:', server.info.uri); }; provision(); ``` ``` -------------------------------- ### Static File Server Example Source: https://hapi.dev/module/inert/api Example code for setting up a basic static file server using the directory handler. ```APIDOC ## Examples ### Static file server The following creates a basic static file server that can be used to serve html content from the `public` directory on port 3000: ```javascript const Path = require('path'); const Hapi = require('@hapi/hapi'); const Inert = require('@hapi/inert'); const server = new Hapi.Server({ port: 3000, routes: { files: { relativeTo: Path.join(__dirname, 'public') } } }); const provision = async () => { await server.register(Inert); server.route({ method: 'GET', path: '/{param*}', handler: { directory: { path: '.', redirectToSlash: true, index: true, } } }); await server.start(); console.log('Server running at:', server.info.uri); }; provision(); ``` ``` -------------------------------- ### Hapi Google Authentication Strategy Setup Source: https://hapi.dev/module/bell/examples Configures a Google authentication strategy with Hapi Bell. It requires developer console setup for clientId and clientSecret. The strategy is defined for the '/bell/door' path and handles all HTTP methods. ```javascript 'use strict'; const Bell = require('..'); const Hapi = require('@hapi/hapi'); const internals = {}; internals.start = async function () { const server = Hapi.server({ host: 'localhost', port: 8000 }); await server.register(Bell); // You'll need to go to https://console.developers.google.com and set up an application to get started // Once you create your app, fill out "APIs & auth >> Consent screen" and make sure to set the email field // Next, go to "APIs & auth >> Credentials and Create new Client ID // Select "web application" and set "AUTHORIZED JAVASCRIPT ORIGINS" and "AUTHORIZED REDIRECT URIS" // This will net you the clientId and the clientSecret needed. // Also be sure to pass the location as well. It must be in the list of "AUTHORIZED REDIRECT URIS" server.auth.strategy('google', 'bell', { provider: 'google', password: 'cookie_encryption_password_secure', isSecure: false, clientId: '', clientSecret: '', location: server.info.uri }); server.route({ method: '*', path: '/bell/door', options: { auth: { strategy: 'google', mode: 'try' }, handler: function (request, h) { if (!request.auth.isAuthenticated) { return 'Authentication failed due to: ' + request.auth.error.message; } return '
' + JSON.stringify(request.auth.credentials, null, 4) + ''; } } }); await server.start(); console.log('Server started at:', server.info.uri); }; internals.start(); ``` -------------------------------- ### 'start' Event Source: https://hapi.dev/api_v=21.3.0 Emitted when the server starts successfully using `server.start()`. ```APIDOC ## 'start' Event ### Description Emitted when the server is started using `server.start()`. ### Handler Signature `function()` ### Example ```javascript server.events.on('start', () => { console.log('Server started'); }); ``` ``` -------------------------------- ### Configure Facebook Authentication with Bell and Hapi.js Source: https://hapi.dev/module/bell/examples This example illustrates the setup for Facebook authentication using the Bell provider in Hapi.js. It requires app credentials from the Facebook developers site and specifies the redirect URI to handle the authentication flow. The example also includes basic error handling for failed authentication. ```javascript 'use strict'; const Bell = require('..'); const Hapi = require('@hapi/hapi'); const internals = {}; internals.start = async function () { const server = Hapi.server({ host: 'localhost', port: 8000 }); await server.register(Bell); // You'll need to go to https://developers.facebook.com/ and set up a // Website application to get started // Once you create your app, fill out Settings and set the App Domains // Under Settings >> Advanced, set the Valid OAuth redirect URIs to include http://
' + JSON.stringify(request.auth.credentials, null, 4) + ''; } } }); await server.start(); console.log('Server started at:', server.info.uri); }; internals.start(); ``` -------------------------------- ### await server.initialize() Source: https://hapi.dev/api_v=21.4.3 Initializes the server, starting caches and finalizing plugin registration, but does not begin listening on the connection port. Errors during initialization may lead to an undefined server state requiring shutdown. ```APIDOC ## await server.initialize() ### Description Initializes the server (starts the caches, finalizes plugin registration) but does not start listening on the connection port. Note that if the method fails and throws an error, the server is considered to be in an undefined state and should be shut down. ### Method `await server.initialize()` ### Endpoint None ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const Hapi = require('@hapi/hapi'); const Hoek = require('@hapi/hoek'); async function example() { const server = Hapi.server({ port: 80 }); await server.initialize(); } ``` ### Response #### Success Response (200) None (returns `undefined`) #### Response Example None ``` -------------------------------- ### Catbox Client API Source: https://hapi.dev/module/catbox/api_v=12.1.1 Documentation for the low-level Catbox Client API, including methods for starting, stopping, getting, setting, and dropping cache items. ```APIDOC ## Client API ### Description The `Client` object provides a low-level cache abstraction for interacting with various cache strategies. ### Methods #### `start()` * **Method**: `await start()` * **Description**: Creates a connection to the cache server. Must be called before any other method. Throws errors if connection fails. #### `stop()` * **Method**: `await stop()` * **Description**: Terminates the connection to the cache server. #### `get(key)` * **Method**: `await get(key)` * **Description**: Retrieves an item from the cache engine. * **Parameters**: * **key** (object) - Required - A cache key object with `segment` and `id` properties. * **Returns**: * `null` if the item is not found. * An object with `item`, `stored` (timestamp), and `ttl` (remaining time-to-live) properties if found. * Throws an error if the request failed. #### `set(key, value, ttl)` * **Method**: `await set(key, value, ttl)` * **Description**: Stores an item in the cache for a specified duration. * **Parameters**: * **key** (object) - Required - A cache key object with `segment` and `id` properties. * **value** (string | object) - Required - The value to be stored. * **ttl** (number) - Required - The time-to-live in milliseconds. * **Throws**: Errors if the operation fails. #### `drop(key)` * **Method**: `await drop(key)` * **Description**: Removes an item from the cache. * **Parameters**: * **key** (object) - Required - A cache key object with `segment` and `id` properties. * **Throws**: Errors if the operation fails. #### `isReady()` * **Method**: `isReady()` * **Returns**: `boolean` - `true` if the cache engine is ready, `false` otherwise. #### `validateSegmentName(segment)` * **Method**: `validateSegmentName(segment)` * **Parameters**: * **segment** (string) - Required - The segment name to validate. * **Returns**: `null` if the segment name is valid, otherwise an `Error` instance. ### Cache Key Object Structure Any method with a `key` argument expects an object with the following properties: * **segment** (string) - Required - A caching segment name string. Used to isolate cached results. * **id** (string) - Required - A unique item identifier string (per segment). Can be an empty string. ``` -------------------------------- ### Manual Loading Example Source: https://hapi.dev/module/h2o2/api Example demonstrating how to manually load and register the h2o2 plugin with a Hapi server. ```APIDOC ## Manual loading ```javascript const Hapi = require('@hapi/hapi'); const H2o2 = require('@hapi/h2o2'); const start = async function() { const server = Hapi.server(); await server.register(H2o2); await server.start(); console.log(`Server started at: ${server.info.uri}`); }; start(); ``` ``` -------------------------------- ### Server Creation Source: https://hapi.dev/api_v=21.3.0 Demonstrates how to create a new Hapi server object with optional configuration. ```APIDOC ## POST /api/users ### Description Creates a new user account. ### Method POST ### Endpoint /api/users ### Parameters #### Query Parameters - **include_profile** (boolean) - Optional - Whether to include the user's profile information in the response. #### Request Body - **username** (string) - Required - The desired username for the new account. - **email** (string) - Required - The user's email address. - **password** (string) - Required - The user's password. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com", "password": "securepassword123" } ``` ### Response #### Success Response (201) - **id** (string) - The unique identifier for the newly created user. - **username** (string) - The username of the created user. - **email** (string) - The email address of the created user. #### Response Example ```json { "id": "user-12345", "username": "johndoe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### Wreck Usage Example Source: https://hapi.dev/family/wreck Demonstrates basic usage of the Wreck library for making a GET request. ```APIDOC ## GET / (Example) ### Description This endpoint demonstrates a basic GET request using the Wreck library. ### Method GET ### Endpoint http://example.com ### Parameters N/A ### Request Body N/A ### Request Example ```javascript const Wreck = require('@hapi/wreck'); const example = async function () { const { res, payload } = await Wreck.get('http://example.com'); console.log(payload.toString()); }; try { example(); } catch (ex) { console.error(ex); } ``` ### Response #### Success Response (200) - **payload** (Buffer) - The response body as a buffer. #### Response Example ``` [Response body content] ``` ``` -------------------------------- ### Server Initialization and Configuration Source: https://hapi.dev/api_v=18.4.2 This section details the `server` object, its initialization with `server([options])`, and its various configuration options and properties. ```APIDOC ## Server Initialization and Configuration ### Description Details the `server` object, its initialization with `server([options])`, and its various configuration options and properties. ### Method `server([options])` ### Endpoint N/A (This is a constructor/initialization function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const Hapi = require('@hapi/hapi'); const server = Hapi.server({ port: 3000, host: 'localhost' }); ``` ### Response #### Success Response (200) N/A (This is an initialization, not a request/response cycle) #### Response Example N/A ``` -------------------------------- ### Create Hapi Server Instance Source: https://hapi.dev/api_v=17.9.4 Initializes a new Hapi server object. The 'options' parameter is an optional configuration object. This example demonstrates setting a sample interval for load event monitoring. ```javascript const Hapi = require('hapi'); const server = Hapi.server({ load: { sampleInterval: 1000 } }); ``` -------------------------------- ### Register Vision with Hapi Server (JavaScript) Source: https://hapi.dev/module/vision Demonstrates how to register the Vision plugin with a Hapi server and start the server. This is a basic setup for enabling template rendering. ```javascript const Hapi = require('@hapi/hapi'); const Vision = require('@hapi/vision'); const server = Hapi.Server({ port: 3000 }); const provision = async () => { await server.register(Vision); await server.start(); console.log('Server running at:', server.info.uri); }; provision(); ``` -------------------------------- ### server.start() Source: https://hapi.dev/api_v=21.3.0 Starts the Hapi server, making it listen for incoming requests. Handles server start errors and provides guidance on recovery. ```APIDOC ## await server.start() ### Description Starts the server by listening for incoming requests on the configured port. If the method fails, it's recommended to shut down the server. ### Method `await server.start()` ### Endpoint N/A (This is a method call on the server object) ### Parameters None ### Request Example ```javascript const Hapi = require('@hapi/hapi'); async function example() { const server = Hapi.server({ port: 80 }); await server.start(); console.log('Server started at: ' + server.info.uri); } ``` ### Response #### Success Response (N/A) This method does not return a value upon success. It starts the server and may throw an error if it fails. #### Response Example N/A ``` -------------------------------- ### Route Invocation: Server Example Source: https://hapi.dev/module/nes/api_v=14.0.1 Demonstrates setting up a Hapi server and registering the NES plugin to handle a 'GET /h' route. It returns 'world!' when invoked. ```javascript const Hapi = require('@hapi/hapi'); const Nes = require('@hapi/nes'); const server = new Hapi.Server(); const start = async () => { await server.register(Nes); server.route({ method: 'GET', path: '/h', config: { id: 'hello', handler: (request, h) => { return 'world!'; } } }); await server.start(); }; start(); ``` -------------------------------- ### Server Configuration and Initialization Source: https://hapi.dev/api_v=19.2.1 Details on configuring and starting a Hapi server, including options for host, port, plugins, and more. ```APIDOC ## Server Configuration and Options ### Description This section details the various options available when configuring a Hapi server. These options control aspects like network settings, plugin management, caching, and debugging. ### Method N/A (Configuration options for `server()`) ### Endpoint N/A ### Parameters #### Server Options - **address** (string) - The address to bind the server to. - **app** (object) - An object for attaching custom application-level data. - **autoListen** (boolean) - Automatically start listening on the specified port. - **cache** (object) - Configuration for the server's caching mechanism. - **compression** (object) - Configuration for response compression. - **minBytes** (number) - Minimum response size in bytes to enable compression. - **debug** (object) - Debugging options for the server. - **host** (string) - The hostname to bind the server to. - **info.remote** (object) - Information about the remote connection. - **listener** (object) - A custom http.Server instance to use. - **load** (object) - Load monitoring configuration. - **mime** (object) - MIME type configuration. - **operations** (object) - Configuration for request operations. - **plugins** (object) - Plugin registration options. - **port** (number) - The port to listen on. - **query** (object) - Query string parsing configuration. - **parser** (function) - Custom query string parser function. - **router** (object) - Router configuration. - **routes** (object) - Default route configuration. - **state** (object) - Server state management configuration. - **tls** (object) - TLS/SSL configuration. - **uri** (string) - The server URI. ### Request Example ```json { "host": "localhost", "port": 3000, "routes": { "cors": true } } ``` ### Response #### Success Response (200) N/A (This describes configuration, not a direct API response.) #### Response Example N/A ``` -------------------------------- ### Rendering a View in Express Source: https://hapi.dev/tutorials/expresstohapi_lang=en_US Shows how to render a view in Express.js using `res.render()`. This example renders the 'index.pug' template and passes context data ('title' and 'message') to it. ```javascript app.get('/', function (req, res) { res.render('index', { title: 'Homepage', message: 'Welcome' }); }); ``` -------------------------------- ### Loading Multiple Hapi Plugins with Options Source: https://hapi.dev/tutorials/plugins_lang=en_US Illustrates registering an array of plugins, where each plugin can have its own specific options. This allows for granular configuration of multiple plugins being loaded simultaneously. ```javascript const start = async function () { const server = Hapi.server(); await server.register([{ plugin: require('plugin1'), options: {} }, { plugin: require('plugin2'), options: {} }]); }; ``` -------------------------------- ### Simulate Hapi Server Request with inject() Source: https://hapi.dev/api_v=21.3.0 Demonstrates how to use `server.inject()` to simulate a GET request to the root path of a Hapi server and log the response result. This is a basic example for testing server routing. ```javascript const Hapi = require('@hapi/hapi'); async function example() { const server = Hapi.server({ port: 80 }); server.route({ method: 'GET', path: '/', handler: () => 'Success!' }); const res = await server.inject('/'); console.log(res.result); // 'Success!' } ``` -------------------------------- ### Hapi Cookie Configuration Source: https://hapi.dev/tutorials/expresstohapi_lang=en_US Demonstrates how to configure cookie settings in hapi using `server.state()` before setting or getting cookies. This sets default options for a cookie named 'data'. ```javascript const Hapi = require('@hapi/hapi'); const server = Hapi.server({ port: 8000 }); server.state('data', { ttl: null, isSecure: true, isHttpOnly: true }); ``` -------------------------------- ### new Server([options]) Source: https://hapi.dev/api_v=16.8.4 Creates a new Server object with optional configuration for application settings, caching, connections, and debugging. ```APIDOC ## `new Server([options])` ### Description Creates a new `Server` object with optional configuration parameters. ### Method `new Server()` ### Endpoint N/A (Constructor) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters `options` - optional configuration object: * `app` (object) - Application-specific configuration. Defaults to `{}`. * `cache` (object|array|function) - Server-side caching configuration using `catbox`. * Can be a prototype function (e.g., `require('catbox-redis')`). * Can be a configuration object with: * `engine` (function|object) - `catbox` strategy. * `name` (string) - Unique identifier for the cache. * `shared` (boolean) - Allows sharing cache segments. Defaults to `false`. * `partition` (string) - Cache partition name. Defaults to `'hapi-cache'`. * Other options passed to the `catbox` strategy. * Can be an array of configuration objects for multiple cache instances. * `connections` (object) - Default connections configuration. * `app` (object) - Application-specific connection configuration. * `compression` (boolean) - Disables response content encoding. Defaults to `true`. * `load` (object) - Connection load limits. * `maxHeapUsedBytes` (number) - Maximum V8 heap size before rejecting requests. Defaults to `0`. * `maxRssBytes` (number) - Maximum process RSS size before rejecting requests. Defaults to `0`. * `maxEventLoopDelay` (number) - Maximum event loop delay before rejecting requests. Defaults to `0`. * `plugins` (object) - Plugin-specific configuration. * `router` (object) - Routing configuration. * `isCaseSensitive` (boolean) - Case sensitivity for URI matching. Defaults to `true`. * `stripTrailingSlash` (boolean) - Removes trailing slashes from paths. Defaults to `false`. * `routes` (object) - Default route options. * `state` (object) - Default state (cookie) configuration. * `debug` (boolean|object) - Debugging log event configuration. Set to `false` to disable all console logging, or an object to specify which events to log. ### Request Example ```json { "options": { "app": { "myCustomSetting": "someValue" }, "cache": { "engine": require('catbox-memory'), "name": "myCache" }, "connections": { "port": 3000, "routes": { "cors": true } }, "debug": { "log": ["error", "warn"], "request": ["received"] } } } ``` ### Response #### Success Response (Instance) - **server** (object) - The created Hapi Server instance. #### Response Example ```json { "server": "[Server Instance]" } ``` ``` -------------------------------- ### Access Hapi Server Info Source: https://hapi.dev/api_v=21.3.0 The 'server.info' property provides read-only information about the server, including its ID, creation and start timestamps, port, host, address, protocol, and URI. This example logs the configured port. ```javascript const Hapi = require('@hapi/hapi'); const server = Hapi.server({ port: 80 }); console.log(server.info.port); // 80 ```