npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

source-configs

v0.3.6

Published

A Node.js module that harvests app-level config values from command line arguments, environment variables, or config files based on a config schema you define within your app.

Downloads

998

Readme

source-configs

Build Status codecov npm

A Node.js module that harvests app-level config values from command line arguments, environment variables, or config files based on a config schema you define within your app. This module was built and is maintained by the Roosevelt web framework team, but it can be used independently of Roosevelt as well.

By default configs matching a given schema are sourced from the following locations in the following order of precedence:

  • Command line argument set in the schema via commandLineArg.
  • Environment variable set in the schema via envVar.
  • Deployment config file declared via:
    • Command line argument: --deploy-config-file or --df.
    • Environment variable: DEPLOY_CONFIG.
    • package.json as a deployConfig field.
  • Default defined in the schema.

Usage

First declare source-configs as a dependency in your app.

Then create a config schema JSON object to tell source-configs what config values to listen for.

Here's a simple example declaring that our application will use a WebSocket with a configurable host, port, and protocol:

// your-schema-js-file.json
{
  websocket: {
    host: {},
    port: {},
    protocol: {}
  }
}

Schema metadata

Schemas support the following metadata for each configurable property in order to create constraints if desired or add additional functionality:

  • description [String]: Describe what this config will be used for.
  • default [any]: Set a default value for this config. If not set, the default is null.
  • values [Array]: Enumerated list of values that are valid. If not set, any value will be valid.
  • commandLineArg [String|Array]: Command line argument(s) to listen for that will set this config. If not set, source-configs will not listen for command line arguments to set the value for this config.
  • envVar [String|Array]: Environment variable(s) to listen for that will set this config. If not set, source-configs will not listen for an environment variable to set the value for this config.

User-defined functions

Additionally, a schema can be a function which has the parent config passed to it as the first argument. To do this create a key/value pair within the schema object:

  • If the schema is stored in a .js file, set the key as the desired function name and the value as the function.
  • If using a .json file to store the schema, set the key as the desired function name and the value as 'user defined function'. Once the .json file is required in, override the key's value with the desired function.

Below is a more complex WebSocket config example leveraging all of the above metadata options:

// your-schema-js-file.json
{
  websocket: {
    host: {
      description: 'WebSocket host URL',
      default: 'localhost',
      commandLineArg: ['--websocket-host-url', '--ws-host', '-h'],
      envVar: ['WEBSOCKET_HOST_URL', 'WS_HOST']
    },
    port: {
      description: 'WebSocket port',
      default: 8081,
      commandLineArg: ['--ws-port', '-p'],
      envVar: 'WS_PORT'
    },
    protocol: {
      description: 'Which WebSocket protocol',
      values: ['ws', 'wss'],
      commandLineArg: '--ws-protocol',
      envVar: 'WS_PROTOCOL'
    },
    url: 'user defined function'
  }
}

Use in your app

Here's an example usage of source-configs using the schema defined above:

const sourceConfigs = require('source-configs')
const schema = require('./your-schema-js-file.json')
schema.websocket.url = function (config) {
  return config.protocol + '://' + config.host + ':' + config.port
}
const config = sourceConfigs(schema)

// access one of the configs
console.log(config.websocket.port)

Custom configuration

In addition to the above instantiation method, source-configs also accepts an optional configuration object that can be passed to the constructor as a second object like so:

const sourceConfigs = require('source-configs')
const schema = require('./your-schema-js-file.json')

const config = sourceConfigs(schema, {
  logging: true,
  sources: [
    'command line',
    'environment variable',
    'deploy config',
    { custom: 'object' }
  ]
})

Available parameters

  • logging: Whether or not source-configs will log to console.

    • Default: [Boolean] true.
  • sources: An array of sources that can be a mix of built-in sources and custom source objects in order of priority.

    • Default [Array]:

        'command line',
        'environment variable',
        'deploy config'
      • Note: built-in sources can also be referenced in multiple ways:

        • Command line: command line or commandLineArg.
        • Environment variable: environment variable or envVar
        • Deploy config: deploy config or deployConfig
    • You can also add custom sources this way by supplying an object to this array:

        'command line',
        'environment variable',
        { custom: 'object' }
      • In this example deploy config is ommitted from the list of sources and a custom object is the last item to source from before defaults.
  • transform: A function that can be used to mutate your config after it has been parsed and sourced but before it gets returned by source-configs.

    • Example:

      const sourceConfigs = require('source-configs')
      const schema = require('./your-schema-js-file.json')
      
      const config = sourceConfigs(schema, {
        transform: (config, commandLineArgs) => {
          // check for a cli flag that wouldn't normally translate into a config
          if (commandLineArgs.switchPort === true) {
            config.websocket.port = 43711
          }
      
          // return the config when done
          return config
        }
      })
      
      // access that config configs
      console.log(config.websocket.port)
      //=> 43711
    • API:

      • transform(config, commandLineArgs): Config transform method.
        • config: The config after being parsed by source-configs.
        • commandLineArgs: CLI flags as parsed by yargs-parser.

Properties of source-configs module

In addition to its constructor, source-configs exposes the following properties:

  • configs [Object]: The resulting configs after running source-config's constructor.
  • commandLineArgs [Array]: All command line arguments passed to your application, including those not listened for by your schema. Powered by yargs-parser.
  • yargsParser [Function]: The instance of yargs-parser that source-configs used to compile all command line arguments passed to your application.
  • printHelp [Function]: A function which will generate a help menu describing the command line arguments defined in the schema. Useful for if you want to define a -h or --help command line argument to print all available supported command line arguments. Just print console.log(config.printHelp()) to print that information to your users.