Electrode Hapi Compatibility Utility

1.3.3 · maintenance · verified Tue Apr 21

The `electrode-hapi-compat` utility provides functions to simplify the creation and detection of Hapi.js plugins compatible across different major versions, specifically Hapi 16 and Hapi 17/18+. It directly addresses the breaking change in Hapi plugin signatures introduced with Hapi 17, offering a `universalHapiPlugin` function. This function allows developers to define distinct plugin implementations for Hapi 16 and Hapi 17+ environments, automatically serving the correct version based on the Hapi framework detected in the host application. The package also includes helper functions such as `isHapi17OrUp` and `isHapi18OrUp` for conditional logic and offers a mechanism to manually set the Hapi version for testing. The current stable version is 1.3.3. While not on a strict regular cadence, it receives updates for broader utility, such as supporting other frameworks like Fastify in earlier minor versions. Its primary differentiator is providing a concise, focused solution for Hapi plugin compatibility across significant framework version boundaries.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to create a Hapi plugin compatible with both Hapi 16 and Hapi 17+ using `universalHapiPlugin`, and how to check the currently detected Hapi version.

const { universalHapiPlugin, isHapi17OrUp } = require("electrode-hapi-compat");
const Hapi = require('@hapi/hapi'); // Ensure Hapi is installed (e.g., npm i @hapi/hapi)

const registers = {
  hapi16: (server, options, next) => {
    console.log("Registering Hapi 16 plugin for:", pkg.name);
    server.decorate('server', 'myHapi16Feature', 'Hapi16 Specific Value');
    next();
  },
  hapi17OrUp: (server, options) => {
    console.log("Registering Hapi 17+ plugin for:", pkg.name);
    server.decorate('server', 'myHapi17Feature', 'Hapi17+ Specific Value');
  }
};

const pkg = {
  name: "MyUniversalCompatPlugin",
  version: "1.0.0"
};

const myUniversalPlugin = universalHapiPlugin(registers, pkg);

async function startServer() {
  const server = Hapi.server({ port: 3000, host: 'localhost' });

  // For demonstration, manually set hapiVersion if Hapi is not installed or detected
  // For example, to simulate Hapi 16:
  // require("electrode-hapi-compat").hapiVersion = 16;

  await server.register({
    plugin: myUniversalPlugin,
    options: {}
  });

  const detectedVersion = require("electrode-hapi-compat").hapiVersion;
  console.log(`Hapi version detected by electrode-hapi-compat: ${detectedVersion}`);
  
  if (isHapi17OrUp()) {
    console.log("Server has myHapi17Feature:", server.myHapi17Feature);
  } else {
    console.log("Server has myHapi16Feature:", server.myHapi16Feature);
  }

  await server.start();
  console.log('Server running on %s', server.info.uri);
}

startServer();

view raw JSON →