Skip to content

akshendra/mapofenv

master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Code

Latest commit

 

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
src
 
 
 
 
 
 
 
 
 
 
 
 

Maps environment variables to JS types.

Example

Environment

Object.assign(process.env, {
  MOE_USE: 'false',
  MOE_MONGO_HOST: '127.0.0.1',
  MOE_MONGO_PORT: '27017',
  MOE_MONGO_DB: 'somedb',
  BOE_MONGO_OPTIONS_READ_PREFERENCE: 'secondary',
  MOE_REDIS_CLUSTER_USE: 'true',
  'MOE_REDIS_CLUSTER_HOSTS_0_HOST': '127.0.0.1', // changed from [0] to _0_ in 0.0.8
  'MOE_REDIS_CLUSTER_HOSTS_0_PORT': '6371',
  'MOE_REDIS_CLUSTER_HOSTS_1_HOST': '127.0.0.2',
  'MOE_REDIS_CLUSTER_HOSTS_1_PORT': '6372',
  'MOE_DARRAY_1_DVALUE': '21',
});

Mapping

const { parse, types } = require('mapofenv');
const { string, boolean, array, number } = types;

const mapping = {
  use: boolean(),
  redis: {
    cluster: {
      use: boolean(),
      hosts: array(2, {
        host: string(),
        port: number(),
      }),
    },
  },
  mongo: {
    host: string(),
    port: number(),
    db: string(),
    options: {
      readPreference: string('primary'),
    },
  },
  un: {
    host: string(),
    port: number(),
  },
  darray: array(2, {
    dvalue: number(20),
    svalue: string(),
  }, [{
    dvalue: 22,
    svalue: 'one',
  }])
};

Mapped Config

const config = parse(mapping, {
  prefix: ['BOE', 'MOE'], // first one wins if none found then null is set
});

Result

// const config will be
{
  use: false,
  redis: {
    cluster: {
      use: true,
      hosts: [{
        host: '127.0.0.1',
        port: 6371,
      }, {
        host: '127.0.0.2',
        port: 6372,
      }],
    },
  },
  mongo: {
    host: '127.0.0.1',
    port: 27017,
    db: 'somedb',
    options: {
      readPreference: 'secondary',
    },
  },
  un: {
    host: null,
    port: null,
  },
  darray: [{
    dvalue: 22,
    svalue: 'one',
  }, {
    dvalue: 21,
    svalue: null,
  }],
}

Available Types

  • string(defaultValue)
  • number(defaultValue)
  • boolean(defaultValue)
  • array(length, itemType, defaultValue)

Instead of given types, any function like the following can be used

function my(stringValueOfEnvVar) {
  // do something to the value
  return transformentValueOfEnvVar;
}

Releases

No releases published

Packages

No packages published