Code Monkey home page Code Monkey logo

catalyst-server's Introduction

Node.js Version NPM Version NPM Downloads No Maintenance Intended

⚠️ Deprecation Notice ⚠️

This package is now deprecated and will not receive any updates in the future.

@vrbo/catalyst-server

Introduction

Catalyst-server is a configuration and composition management tool for Hapi.js applications. It allows for composition and configuration that is environment aware and extensible for a web application. This is managed from one or more manifest.json files. The userConfigPath accepts a string that is a path to a single manifest.json file, or an array of path strings to support merging multiple manifest files. Duplicate keys in configuration files will be overwritten upon merging. If an array is passed, values of the config file that is the last index of userConfigPath takes precedence when merging, otherwise values from the single config file passed to userConfigPath takes precedence. The server also will include sensible defaults and implementations (like hapi-pino for logging and crumb for CSRF)

Usage

  1. Install catalyst-server and hapi into an empty node project with npm i @vrbo/catalyst-server @hapi/hapi
  2. Create an index.js file for starting your server (example below).
  3. Create a manifest.json for composition and configuration (example below).
  4. Start your app node index.js

index.js

const Catalyst = require('@vrbo/catalyst-server');
const Path = require('path');

// Init a new Catalyst server, and pass the path to your manifest file to the userConfigPath option to compose your app plugins
async function start(options = {}) {
    const server = await Catalyst.init({
        ...options,
        userConfigPath: Path.resolve(__dirname, 'manifest.json')
    });

    await server.start();

    server.log(['info'], `server running: ${server.info.uri}`);

    return server;
}

start();
// Alternatively, pass an array of paths to compose your app plugins from separate manifest files.
const server = await Catalyst.init({
    userConfigPath: [
        path.resolve(__dirname, 'manifest.json'),
        path.resolve(__dirname, '/external/manifest.json')
    ]
});

manifest.json

{
     // server configuration and application context variables.
    "server": {
        "app": {}
    },
    // Hapi plugins
    "register": {},
    // Hapi routes
    "routes": []
}

Catalyst.init() Options

  • userConfigPath - Path to the json configuration file (see examples).
  • onConfig - Hook for modifying config prior to creating list of plugins to register (can be async). (config) => {return config;}
  • defaults - default pre-resolved configuration values. Can be an object or a path to a json file.
  • overrides - optional override pre-resolved configuration values. Can be an object or a path to a json file.
  • baseDir - Alternative location to base shortstop relative paths from.
  • environment - Additional criteria for confidence property resolution and defaults to { env: process.env }.
  • shortstopHandlers - Object for additional shortstop handlers.
  • enableShutdownListeners - Flag indicator for enabling or disabling execution of shutdown listeners, default 'true'

Configuration and Composition

Catalyst-server uses @vrbo/steerage to configure and compose your application. It is environment aware and has some configuration protocols to resolve paths, read environment variables, import other JSON files, and more.

Basic example

At its core, catalyst-server loads a manifest.json file to initialize and start up a Hapi.js server. This file has a section for application configuration and composition via registering plugins.

Below is a basic example of a manifest.json file:

manifest.json

{
     // server configuration and application context variables.
    "server": {
        "app": {
            "urlPrefix": "temp/",
            "siteTitle": "temp site"
        }
    },
    // Hapi plugins
    "register": {
        "inert": {
            "plugin": "require:@hapi/inert"
        },
        "vision": {
            "plugin": "require:@hapi/vision",
            "options": {
                "engines": {
                    "html": "require:handlebars"
                },
                "path": "path:./templates"
            }
        }
    },
    // Hapi routes
    "routes": [
        {
            "method": "GET",
            "path": "/my-file.txt",
            "handler": {
                "file": "path:./my-file.txt"
            }
        }
    ]
}

You can access all the configuration values in your code from the server.app.config object. So the code to retrieve the example values looks like this:

const urlPrefix = server.app.config.get('urlPrefix');
const siteTitle = server.app.config.get('siteTitle');

The register block registers the plugins referenced. In this example, it is using shortstop to resolve node modules using require:[module] and resolve paths using path:[file_path].

Catalyst-server ships with the following shortstop resolvers by default:

  • file - read a file.
  • path - resolve a path.
  • base64 - resolve a base64 string.
  • env - access an environment variable.
  • require - require a javascript or json file.
  • exec - execute a function in a file.
  • glob - match files using the patterns shell uses.
  • import - imports another JSON file, supports comments.
  • eval - safely execute a string as javascript code.

Environment Aware

@vrbo/steerage uses confidence to give you the ability to build environmentally aware servers. See the example manifest.json file below.

Environment based manifest.json

{
     // server configuration and application context variables.
    "server": {
        "app": {
            "urlPrefix": {
                "$filter": "env.NODE_ENV",
                "production":"/application",
                "$default":"/temp"
            }
        }
    },
    // Hapi plugins
    "register": {
        "crumb": {
            "plugin": "require:crumb",
            "options": {
                "cookieOptions": {
                    "isSecure": {
                        "$filter": "env.NODE_ENV",
                        "production": true,
                        "$default": false
                    }
                },
                "restful": true
            }
        }
    }
}

In this example, the $filter and $default fields allow for filtering based on a resolver like env.NODE_ENV.

The $filter field evaluates the environment variable NODE_ENV. Then, it will look to the following fields for a match in the keys for that value. Otherwise, the $default value is used. So the configuration values and options for plugins will change based on the environment variable NODE_ENV.

This is what the above manifest configuration will return in code for different environments:

// ENVIRONMENT VARIABLE NODE_ENV='development'
const urlPrefix = server.app.config.get('urlPrefix');
// returns '/temp'
// crumb will NOT use secure cookies.

// ENVIRONMENT VARIABLE NODE_ENV='production'
const urlPrefix = server.app.config.get('urlPrefix');
// returns '/application'
// crumb WILL use secure cookies.

Using a filter, you can easily enable/disable a plugin for a given environment. See the code below for an example, where we disable hapi-pino in development mode, and enable it in all other environments:

{
    "register": {
        "hapi-pino": {
            "enabled": {
                "$filter": "env.NODE_ENV",
                "production": true,
                "$default": false
            }
        }
    }
}

Advanced

Here are some examples of the shortstop resolvers which make handling complex configuration and composition rather straight forward.

file: Reading a file into a value.

  • loads the file pgp_pub.key and will set the value key to the contents of that file.
    {
        "key": "file:./pgp_pub.key"
    }

path: Resolve a path.

  • will resolve the path of ./templates and will set the value path to the fully resolved path.
    {
        "path": "path:./templates"
    }

base64: Resolve a base64 string.

  • will decode the base64 string SGVsbG8= and will set the bytes value to a buffer from the base64 string.
    {
        "bytes": "base64:SGVsbG8="
    }

env: Access an environment variable.

  • will evaluate the environment variable PG_HOST and will set the dbHost value to the environment variable value.
    {
        "dbHost": "env:PG_HOST"
    }

require: Require a javascript or json file.

  • will load the node module inert and will set the register to what that module exports. This works for js files in you application.
    {
        "plugin": "require:@hapi/inert"
    }

exec: Execute a function in a file.

  • will load the file callStatus.js and will run the exported function get and whatever value is return will be set for the status value.
    {
        "status": "exec:./callStatus#get"
    }

glob: Match files using the patterns shell uses.

  • will use glob to evaluate ./assets/**/*.js and sets the value of files to an array of files that match the glob string.
    {
        "files": "glob:./assets/**/*.js"
    }

import: Imports another JSON file, supports comments.

  • will load a json file ./data/salt.json, evaluate it (ignoring comments) and set data to that value.
    {
        "data": "import:./data/salt.json"
    }

eval: Safely execute a string as javascript code.

  • will use vm to evaluate the string and set the start to the current date time as an ISO string.

    {
        "start": "eval:new Date().toISOString()"
    }
  • eval can also be used to reference other values in the manifest. In the above example the child/value in server/app will be set to 'abc_xyz'.

    {
        "server": {
            "app":{
                "first": "abc",
                "second": "xyz",
                "child": {
                    "value":"eval:${server.app.first}_${server.app.second}"
                }
            }
        }
    }

Example Code

See the examples folder for example code.

Further Reading

catalyst-server's People

Contributors

aaestrada avatar bensbigolbeard avatar dependabot[bot] avatar ianwhitedeveloper avatar joonastanner avatar kisaiev avatar mcjfunk avatar renovate-bot avatar renovate[bot] avatar sbanoseg avatar semantic-release-bot avatar shellbj avatar skphi13 avatar smilebot avatar tuckbick avatar yosafateg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

catalyst-server's Issues

Dependency Dashboard

This issue provides visibility into Renovate updates and their statuses. Learn more

This repository currently has no open or pending branches.


  • Check this box to trigger a request for Renovate to run again on this repository

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.