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

dollar-config

v0.1.18

Published

Static config with dynamic settings

Downloads

1

Readme

Dollar config

Dollar config lets you keep dynamic settings in a declarative way and query them with runtime params.

Build Status npm version Coverage Status

Installation

npm install dollar-config

Setup

const DollarConfig = require('dollar-config');

const config = new DollarConfig(require('config.json'));

Usage

config.get('path.to.setting', runtimeParams);

Examples

Static setting

No magic here.

{
  "foo": 1
}
config.get('foo');
> 1

$default

Provides a fallback for an absent setting.

{
  "foo": 1,
  "$default": 0
}
config.get('bar');
> 0

$param

Looks up a param and returns its value.

{
  "foo": {
    "$param": "bar"
  }
}
config.get('foo', { bar: 1 });
> 1

Use an array to provide a default value:

{
  "foo": {
    "$param": [ "bar", 0 ]
  }
}
config.get('foo', { baz: 1 });
> 0

$template

Replaces ${paramName} with param value.

{
  "greeting": {
    "$template": "Hello, ${name}!"
  }
}
config.get('greeting', { name: 'John' });
> Hello, John!

$guard

Picks the first truthy param and returns correspondent setting.

Falls back to an optional $default if none of the params is truthy.

N.B. $default, if present, must be the last item for lookup performance.

{
  "foo": {
    "$guard": [
      [ "bar", "no luck" ],
      [ "baz", "close, but no cigar" ],
      [ "qux", "you are the champion" ],
      [ "$default", "oops" ]
    ]
  }
}
config.get('foo', { bar: false, baz: '', qux: 1 });
> you are the champion

config.get('foo', {})
> oops

$switch

Matches param value to a list of cases and picks correspondent setting.

Falls back to an optional $default if no match is found.

N.B. $default, if present, must be the last item for lookup performance.

{
  "meal": {
    "$switch": [
      "dayOfTime",
      [
        [ "morning", "breakfast" ],
        [ "midday", "lunch" ],
        [ "evening", "dinner" ],
        [ "$default", "fridge" ]
      ]
    ]
  }
}
config.get('meal', { dayOfTime: 'midday' });
> lunch

config.get('meal', { dayOfTime: 'night' });
> fridge

$function

Calls the referenced function and returns it's value.

Functions are provided as an option to config constructor.

Each function recevies params as a single argument.

{
  "expectedSalary": {
    "$function": "double"
  }
}
const config = new DollarConfig(require('config.json'), {
    functions: {
        double: (params) => params.currentSalary * 2
    }
});

config.get('expectedSalary', { currentSalary: 500 });
> 1000

Nested settings/params/functions

Deep properties are accessible with dot-notation:

{
  "foo": {
    "bar": {
      "$param": "baz.qux"
    }
  }
}
config.get('foo.bar', { baz: { qux: 1 } });
> 1

Nested $-keywords

You can mix and match $-keywords to get the desired effect:

{
  "foo": {
    "$switch": [
      "bar",
      [
        [
          "baz",
          {
            "$guard": [
              [ "qux", { "$param": "xyz" } ]
            ]
          }
        ]
      ]
    ]
  }
}
config.get('foo', { bar: 'baz', qux: true, xyz: 1 });
> 1

Binding

The .bind() method clones your config, converting all dynamic keys to getters, so that you can use them as a normal object:

const config = new DollarConfig({
    foo: 1,
    bar: { $param: 'baz' }
});

config.bind({ baz: 2 });
> { foo: 1, bar: 2 }

Because all dynamic keys are evaluated lazily, you can even make self-references:

const config = new DollarConfig({
    foo: { $param: 'baz' },
    bar: { $param: 'config.foo' }
});

const params = { baz: 1 };
params.config = config.bind(params);

params.config
> { foo: 1, bar: 1 }

After the first invocation getters replace themselves with evaluated values (a.k.a memoization):

let i = 1;
const config = new DollarConfig(
    { foo: { $function: 'bar' } },
    { functions: { bar: () => i++ } }
);
const boundConfig = config.bind({});

boundConfig.foo
> 1

boundConfig.foo
> 1

Express middleware

Dollar config express middleware binds provided config to the express req and puts the result into req.config:

{
  "foo": {
    "$param": "query.bar"
  }
}
const dollarConfigMiddleware = require('dollar-config/middleware');

app.use(dollarConfigMiddleware(require('config.json'));

// /?bar=1
app.use((req, res, next) => {
    req.config.foo === 1 // true
});

The middleware accepts dollar config instances as well:

const dollarConfigMiddleware = require('dollar-config/middleware');

const config = new DollarConfig(require('config.json'));

app.use(dollarConfigMiddleware(config));

Validation

You can use special ajv plugin to validate dollar-configs against JSON schemas.

const ajv = require('dollar-config/ajv')(new Ajv());
const validate = ajv.compile(require('schema.json'));

Or, with ajv-cli:

ajv validate -d config.json -s schema.json -c dollar-config/ajv

The plugin introduces a custom dynamic keyword which accepts any valid JSON schema inside it:

{
  "type": "object",
  "properties": {
    "foo": {
      "dynamic": {
        "type": "number"
      }
    }
  }
}
validate({ foo: 1 });
> true

validate({ foo: { $param: 'bar' } });
> true

The plugin checks that leaf values of $-keywords match original schema:

validate({ foo: { $param: [ 'bar', 1 ] } });
> true

validate({ foo: { $param: [ 'bar', '1' ] } });
> false (expected number, got string)

validate({ foo: { $guard: [ [ 'bar': '1' ] ] } });
> false (expected number, got string)

Using $template implies that the original schema is string:

validate({ foo: { $template: '${bar}/${baz}' } });
> false (expected original schema to be string, got number)

Building

Sometimes you want to have separate configs for different environments. Dollar config lets you keep all the settings in one source config and generate per-environment configs. dollar-config/build can be used to inline predefined params. Other dynamic params are returned as-is.

{
  "backendUrl": {
    "$switch": [
      "environment",
      [
        [ "prestable", "https://prestable-backend/" ],
        [ "$default", "https://production-backend/" ]
      ]
    ]
  },
  "backendQuery": {
    "foo": { "$param": "bar" }
  }
}
const buildConfig = require('dollar-config/build');

const config = require('config.json');

buildConfig(config, { environment: 'prestable' });
>
{
  backendUrl: "https://prestable-backend/",
  backendQuery: {
    "foo": { "$param": "bar" }
  }
}

buildConfig(config, { environment: 'production' });
>
{
  backendUrl: "https://production-backend/",
  backendQuery: {
    "foo": { "$param": "bar" }
  }
}