hapi pal
Getting Started API Docs Best Practices hapi pal

Reference Version:

  • boilerplate
  • schwifty
  • schmervice
  • toys
  • lalalambda
  • ahem
  • avocat
  • hecks
  • hpal
  • hpal-debug
  • haute-couture
  • tandy
  • confidence
  • hodgepodge
  • underdog
github | npm

ahem

hapi plugins as libraries

Build Status Coverage Status

Lead Maintainer - Devin Ivy

Installation

npm install @hapipal/ahem

Usage

See also the API Reference

Ahem is intended for use with hapi v20+ and nodejs v16+ (see v2 for lower support). Ensure you've installed @hapi/hapi within your project.

Ahem's purpose is to encourage new possibilites for hapi plugin composition and portability. It's a small tool that offers only subtly different functionality from glue; but unlike glue, ahem's API is designed to strongly reinforce the perspective of hapi plugins as being instantiable general-purpose libraries, and not just web servers.

Ahem has applications in building non-server projects using hapi, creating servers with multiple connections, safely sharing functionality across plugins, and testing hapi plugins (particularly complex application plugins that use schwifty models or schmervice services). Finally, ahem is compatible with schmervice, and plugins can be used as services under schmervice. We think the collection of examples below should help to illustrate.

Examples

Treat vision as a library

The most basic usage of ahem is to instance a plugin with some plugin options. Here we treat vision as an adapter-based templating library rather than as a hapi plugin.

// npm install @hapipal/ahem @hapi/hapi @hapi/vision handlebars
const Vision = require('@hapi/vision');
const Handlebars = require('handlebars');
const Ahem = require('@hapipal/ahem');

// Before continuing, create a template:
// mkdir templates && echo 'Hello, {{name}}!' > templates/hello.hbs

(async () => {

    const vision = await Ahem.instance(Vision, {
        engines: { hbs: Handlebars },
        relativeTo: __dirname,
        path: 'templates'
    });

    const message = await vision.render('hello', { name: 'Clarice' });

    console.log(message); // Hello, Clarice!
})();

Instantiate your application with its dependencies

If your application has external plugin dependencies then you can specify those using the register option.

// npm install @hapipal/ahem @hapi/hapi @hapipal/schwifty knex sqlite3
const Schwifty = require('@hapipal/schwifty');
const Ahem = require('@hapipal/ahem');
const App = require('./app');

// Below assumes your application plugin
// uses schwifty and has an objection Users model.

(async () => {

    const app = await Ahem.instance(App, {}, {
        register: [
            {
                plugin: Schwifty,
                options: {
                    knex: {
                        client: 'sqlite3',
                        useNullAsDefault: true,
                        connection: {
                            filename: ':memory:'
                        }
                    }
                }
            }
        ]
    });

    const { Users } = app.model();

    const paldo = await Users.query().insertAndFetch({ name: 'paldo' });

    console.log(paldo);
})();

Instantiate your application, controlled by a server

You might want to use one of your application plugins within a separate hapi project or deployment. In this case you usually want the instance of your application to be "tied" to the lifecycle of the primary hapi server of that project: when you initialize/start/stop the primary server you would like your application instance to do the same. In hapi jargon you want your application to be "controlled" by that server (see server.control() for more info). Ahem can take care of this for you, if you simply provide the primary server as an argument.

// npm install @hapipal/ahem @hapi/hapi
const Hapi = require('@hapi/hapi');
const Ahem = require('@hapipal/ahem');
const App = require('./app');

(async () => {

    const server = Hapi.server();

    const app = await Ahem.instance(server, App);

    // app is not yet initialized

    await server.initialize();

    // app is now initialized too

    await server.stop();

    // app is now stopped too
})();
Using ahem as a plugin for controlled usage

Ahem can also be used as a plugin, e.g. for repeated "controlled" usage by the same server. This style emphasizes the relationship between hapi's plugin registration with server.register() versus ahem's plugin instancing: the former has a major effect on server and the latter does not. An equivalent way to write the above example using ahem as a plugin would look like this.

// npm install @hapipal/ahem @hapi/hapi
const Hapi = require('@hapi/hapi');
const Ahem = require('@hapipal/ahem');
const App = require('./app');

(async () => {

    const server = Hapi.server();

    await server.register(Ahem);

    const app = await server.instance(App);

    // app is not yet initialized

    await server.initialize();

    // app is now initialized too

    await server.stop();

    // app is now stopped too
})();

Treat vision as a service

Schmervice recognizes hapi plugin instances as valid services, which means that you can register an instance created by ahem with schmervice without any friction. Schmervice will use the name of the plugin (i.e. it's name attribute) as the service's name by default. You can specify a different name using Schmervice.withName() if desired.

// npm install @hapipal/ahem schmervice @hapi/hapi @hapi/vision handlebars
const Hapi = require('@hapi/hapi');
const Vision = require('@hapi/vision');
const Handlebars = require('handlebars');
const Schmervice = require('@hapipal/schmervice');
const Ahem = require('@hapipal/ahem');

// Before continuing, create a template:
// mkdir templates && echo 'Hello, {{name}}!' > templates/hello.hbs

(async () => {

    const server = Hapi.server();

    await server.register(Schmervice);

    const vision = await Ahem.instance(Vision, {
        engines: { hbs: Handlebars },
        relativeTo: __dirname,
        path: 'templates'
    })

    server.registerService(vision);

    const { vision: templatingService } = server.services();

    const message = await templatingService.render('hello', { name: 'Clarice' });

    console.log(message); // Hello, Clarice!
})();

Deploy a server with many connections

In hapi v17 hapi dropped support for multiple connections. Ahem offers a convenient way to reintroduce multiple connections to your project. Below we demonstrate the use-case of redirecting HTTP to HTTPS in a single process using the server option to specify a port. Note that this is another example of "controlled" usage similar to this example above.

// npm install @hapipal/ahem @hapi/hapi hapi-require-https
const Fs = require('fs');
const Hapi = require('@hapi/hapi');
const Ahem = require('@hapipal/ahem');
const RequireHttps = require('hapi-require-https');
const App = require('./app');

// Note, the example below utilizes ports 80 and 443 which
// typically require special privileges. It's more common
// to deploy node behind a reverse proxy in production.

(async () => {

    const server = Hapi.server({
        port: 443,
        tls: {
            key: Fs.readFileSync('key.pem'),
            cert: Fs.readFileSync('cert.pem')
        }
    });

    await server.register(App);

    await Ahem.instance(server, RequireHttps, {
        proxy: false    // See https://github.com/bendrucker/hapi-require-https#proxy
    }, {
        server: {
            port: 80
        }
    });

    await server.start();

    console.log(`Server started at ${server.info.uri}`);
})();

Instance vision as a factory

Ahem offers an additional style for wrapping hapi plugins into a library: you can turn a plugin into a factory for an instance using Ahem.toFactory(plugin).

// npm install @hapipal/ahem @hapi/hapi @hapi/vision handlebars
const Vision = require('@hapi/vision');
const Handlebars = require('handlebars');
const Ahem = require('@hapipal/ahem');

// Before continuing, create a template:
// mkdir templates && echo 'Hello, {{name}}!' > templates/hello.hbs

(async () => {

    const createVision = Ahem.toFactory(Vision);

    const vision = await createVision({
        engines: { hbs: Handlebars },
        relativeTo: __dirname,
        path: 'templates'
    });

    const message = await vision.render('hello', { name: 'Clarice' });

    console.log(message); // Hello, Clarice!
})();

Advanced usage

Ahem has a handful of other options that can be used too. Check out the API Reference for more info.

// npm install @hapipal/ahem @hapi/hapi @hapi/vision handlebars
const Vision = require('@hapi/vision');
const Handlebars = require('handlebars');
const Ahem = require('@hapipal/ahem');

// Before continuing, create a template:
// mkdir templates && echo 'Hello, {{name}}!' > templates/hello.hbs

(async () => {

    const server = Hapi.server();

    await Ahem.instance(server, Vision, {
        engines: { hbs: Handlebars },
        relativeTo: __dirname,
        path: 'templates'
    }, {
        controlled: false,
        initialize: true,
        decorateRoot: false,
        decorateControlled: false
    });

    const message = await server.render('hello', { name: 'Clarice' });

    console.log(message); // Hello, Clarice!
})();

API

Utilities for treating hapi plugins as standalone libraries.

Note

Ahem is intended for use with hapi v20+ and nodejs v16+ (see v2 for lower support). Ensure you've installed @hapi/hapi within your project.

Ahem

await Ahem.instance([server], plugin, [options, [compose]])

Returns an instance of plugin, i.e. a plugin-server, where plugin is a hapi plugin.

  • server - an optional hapi server, typically used to control the returned plugin instance. See also compose.controlled below.
  • plugin - a hapi plugin.
  • options - plugin options for plugin.
  • compose - options related to the composition of server, plugin, and the returned plugin instance.
    • compose.server - hapi server options. These options will be used to create the root server for plugin to live on. Note that this cannot be set when server is passed but compose.controlled is false: in that case plugin is registered directly to server, and an additional hapi server will not be created.
    • compose.register - additional plugins to register to the same server as plugin, usually to fulfill plugin's dependencies. This may take the shape { plugins, options } or just plugins, where plugins and options are defined as the arguments to server.register(plugins, [options]).
    • compose.controlled - when a server is specified but this is set to false, plugin will be registered directly to server. By default plugin will be instanced on a separate server, but controlled by server, meaning that it's tied to server's initialize/start/stop lifecycle.
    • compose.initialize - may be set to true or false to determine whether to initialize the plugin instance. In a controlled situation (per compose.controlled) this option defaults to false; when set to true, server will be initialized (in turn the plugin instance is also intialized). In a non-controlled situation this option defaults to true; when set to false, the returned plugin instance will not be initialized.
    • compose.decorateRoot - determines whether or not the returned plugin instance should have a root decoration that references the root server to which it is registered. Defaults to true unless server is specified but compose.controlled is false.
    • compose.decorateController - determines whether or not the returned plugin instance should have a controller decoration that references the controlling server. Defaults to true when in a controlled situation (per compose.controlled).

Example

// npm install @hapipal/ahem @hapi/hapi @hapi/vision handlebars
const Vision = require('@hapi/vision');
const Handlebars = require('handlebars');
const Ahem = require('@hapipal/ahem');

// Before continuing, create a template:
// mkdir templates && echo 'Hello, {{name}}!' > templates/hello.hbs

(async () => {

    const vision = await Ahem.instance(Vision, {
        engines: { hbs: Handlebars },
        relativeTo: __dirname,
        path: 'templates'
    });

    const message = await vision.render('hello', { name: 'Clarice' });

    console.log(message); // Hello, Clarice!
})();

Ahem.toFactory(plugin)

Returns a function async function([server], [options, [compose]]) identical in behavior to Ahem.instance([server], plugin, [options, [compose]]) but with plugin fixed. This allows hapi plugins to easily provide an interface for standalone usage.

Example

// my-plugin.js
const Ahem = require('@hapipal/ahem');

exports.plugin = {
    name: 'my-plugin',
    register(server, options) {
        // ...
    }
};

exports.create = Ahem.toFactory(exports.plugin);
// index.js
const Hapi = require('@hapi/hapi');
const MyPlugin = require('./my-plugin');

(async () => {

    // Your plugin can be used without explicitly utilizing hapi or ahem:

    const app = await MyPlugin.create({/* options */});

    // Or it can be registered normally as a hapi plugin:

    const server = Hapi.server();

    await server.register({
        plugin: MyPlugin,
        options: {/* options */}
    });
})();

The hapi plugin

The purpose of this plugin is to expose the functionality of Ahem.instance() as a server decoration.

Registration

Ahem may be registered multiple times—it should be registered in any plugin that would like to use any of its features. It takes no plugin options.

Server decorations

await server.instance(plugin, [options, [compose]])

Identical in behavior to Ahem.instance([server], plugin, [options, [compose]]) but with server fixed. This is typically used to instance plugin while ensuring it's controlled by server. It can be thought of as the less effectful version of server.register(): rather than registering plugin to server, we instead create an instance of plugin and tie it to server's initialize/start/stop lifecycle.

Example
// npm install @hapipal/ahem @hapi/hapi
const Hapi = require('@hapi/hapi');
const Ahem = require('@hapipal/ahem');
const App = require('./app');

(async () => {

    const server = Hapi.server();

    await server.register(Ahem);

    const app = await server.instance(App);

    // app is not yet initialized

    await server.initialize();

    // app is now initialized too

    await server.stop();

    // app is now stopped too
})();

Glossary

Plugin-server

// This is a hapi plugin
exports.plugin = {
    name: 'my-plugin',
    register(server, options) {
        //   ^^^^^^ This is a plugin-server
    }
};

If you've written a hapi plugin then you're already familiar with this idea, although you might not have a name for it. Every hapi plugin defines a register() function: async register(server, options). The server passed to this function by hapi is what we call the "plugin-server." It is different from the server returned by Hapi.server(), sometimes called the "root server", because plugin-servers are scoped to a realm created by hapi specific to the registration of that plugin.

Hapi Pal
Home
API Docs Best Practices
Helpful Links
Discussion Board Code of Conduct Edit This Site Slack (#hapipal) Medium Blog Designer, Justin Varberakis hapi.dev
Made with in Portland, Maine