Skip to content

dnunes/autoenvconfig

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

67 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

AutoEnvConfig

Environment config that Just Works™!

Stop worrying about the hassle of loading environment config files everywhere, config files with missing entries or schemas that gets old when you forget to add a new config key to it.

AutoEnvConfig is a fully-tested*, no-nonsense, no-dependencies package to help you keep your ever expanding project under control. *(bear with me on the beta features)

AutoEnvConfig was designed with simple but very powerful goals:

  • Blazingly fast: it caches everything it can, loads your files only once and check your schema on load, not on usage;
  • No extra configuration needed: this package follows the idea of convention over configuration, so it keeps the required environment files to a minimum and there is nothing to thinker with before start using it;
  • Never out of sync: when loading the environment configuration file, it checks the schema for missing or extra keys, alerting you when you are missing some key in your config or in your schema file;
  • Auto load of the right config file: you can set the root path of the project in the environment config file and it will load automatically;
  • Possible local eventual persistence (beta): you can overwrite data by code and have it persisted across restarts (or even deploys!) whenever needed. Things like general settings' dashboard for a small project gets really fast and easy (look, ma!, no databases!). You can backup your persistence file whenever you need or simply merge it with your env config periodically to make changes definitive.

To use it right away, npm install it and follow the super simple Quick Start Guide.

For more details, check out the Conventions and Public Methods API.

The simplest way to install this package is using npm:

$ npm i AutoEnvConfig

You can also manually download any release from our GitHub repository on the releases page or try the latest stable source. The links and info are also available on the project page.

There are just four steps needed to start using this package:

  1. Create a folder named envs on your project's root;
  2. Create a config.schema file with your schema;
  3. Create a ENVNAME.json file for your environments with their specific configuration (where ENVNAME is whatever name you wish to use);
  4. Load the package. Done.

In your code:

const AutoEnvConfig = require('autoenvconfig');

let isValuePresent = AutoEnvConfig.has('deep.key.supported'));
if (isValuePresent) {
  let valueFromConfig = AutoEnvConfig.get('deep.key.supported'));
  console.log(valueFromConfig); //"myValue"
}

let itDoesDefaults = AutoEnvConfig.get('invalid.key', 'default');
console.log(itDoesDefaults); //"default"

One of the nicest features of the package is that you don't need to specify the environment, as it will magicly detect and load the correct file based on some values. This auto generated instance is called magic instance.

For the magic load to happen, your config.schema and ENVNAME.json files must have a _path key with the path of your project's root. It will find the correct environment checking this value by default. You can, however, safely ignore this convention and manually specify the file name if needed.

The schema and environment config files are simple JSON files. The only limit for the keys is the dot character (".") which is forbidden (because it is used as a separator when loading), but I suggest you to limit your keys to alphanumeric chars for simplicity.

In the schema files, every key MUST be prefixed with either # or ?, indicating mandatory or optional key, respectively.

{
  "# _path": "",

  "# id": "",
  "# envtype": "",

  "# requiredKey": "",
  "? deep": {
    "? key": {
      "# supported": "myValue",
      "? asWell": "otherValue"
    }
  }
}

You can have a required key inside an optional object (in this sample, the supported required key is inside optional deep and key objects), so that you can omit the whole object (it will use the defaults), but if it exists in the environment config file, it must include at least these required keys.

{
  "_path": "/home/dnunes/code/node/autoenvconfig",

  "id": "dev",
  "envtype": "local",

  "requiredKey": "value"
}

If you need to overwrite some settings through code you can use AutoEnvConfig.set(<key>, <value>)) method (or its instance counterpart). This change will not survive restarts or new deploys, though. For any time you need to have something persisted across local restarts or even deploys, you can now use AutoEnvConfig.persist(<key>, <value>)) and it will be loaded automatically on the next run/instance creation.

The persistence file defaults to the path envs/ENVNAME.persist.json but you can freely configure it using the _persistFile key in your ENVNAME.json. The path resolution defaults to the root of your project, so a value of custom.persist.json for the _persistFile key would create the persistence file in your project's root folder.

To avoid filling your I/O with multiple writes to disk, it will only persist the data periodically and efficiently using a minimum interval setting and dirty detection logic, so it's safe to call persist methods multiples times a second with no impact on performance whatsoever. An even improved logic suitable for eventual bursts in settings will be implemented in the future.

All the methods can be called in a specific instance (from a AutoEnvConfig.load call) or in the magic instance. You can save a reference for the magic instance using a AutoEnvConfig.load() call and call methods on this instance as well and it will work exactly the same as calling the methods directly on the package. The only exception is the "AutoEnvConfig.enablePersistence()" and "AutoEnvConfig.disablePersistence()"

You can override the default file and bypass the environment file search routine by calling the load method:

//will load envs/other.json
AutoEnvConfig = require('autoenvconfig').load('other');
AutoEnvConfig.get('key.in.other.file');

You can also load multiple configs if ever needed:

AutoEnvConfig = require('autoenvconfig');

//load the right env based on "_path" config value
let rightConfig = AutoEnvConfig.load();
rightConfig.get('key.in.right.file');

//load "envs/other.json"
let otherConfig = AutoEnvConfig.load('other');
otherConfig.get('key.in.other.file');

//load "envs/oneMore.json"
let oneMoreConfig = rightConfig.load('oneMore.json');
oneMoreConfig.get('key.in.onemore.file');

Note that you can call load directly on the package or on any AutoEnvConfig object returned by the load method.

  • 1.0.0 Added local eventual persistence (beta) and basic unit tests this new feature;

  • 0.1.6 Added unit tests for "set" methods and finished pending test for internal cache;

  • 0.1.5 Added "set" methods and started improving documentation for API. Missing unit tests on it;

  • 0.1.4 100% functions coverage and almost 100% branch coverage;

  • 0.1.3 Removed "get" aliases, fixed "instance.get()" and added "has" methods;

  • 0.1.2 Improved syntaxerror handling in schema files;

  • 0.1.1 Bugfix for using natural expected behavior after .load('name');

  • 0.1.0 Initial release.

Created and maintained (with much ♡) by diego nunes

Donations with Bitcoin to 1PQyeHqusUj3SuTmw6DPqWSHptVHkYZ33R:

1PQyeHqusUj3SuTmw6DPqWSHptVHkYZ33R