Skip to content

Commit

Permalink
feat: Add env parser and tests
Browse files Browse the repository at this point in the history
Add module for parse enviroment variables and conver it to Map.<string, string>.
  • Loading branch information
CheerlessCloud committed May 29, 2017
1 parent 50d3446 commit cee0ff6
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/env-parser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const normalFieldName = /^[A-Z\d_\-.:]+$/i;
const flatOnlyFieldName = /^[A-Z\d_-]+$/i;

/**
* @param {object=} options
* @param {boolean=} [options.flatOnly=false]
* @return {Map.<string, string>}
*/
function envParse(options = {}) {
const flatOnly = options.flatOnly || false;

const { env } = global.process;

return new Map(Object.keys(env)
.map((key) => {
if (!key.match(flatOnly ? flatOnlyFieldName : normalFieldName)) {
throw Error(`Unsupported env field name: ${key}`);
}

const newKey = key.toLowerCase()
.replace(/([:_-])([a-z\d])/g, str => str[1].toUpperCase());

return [newKey, env[key]];
}));
}

export default envParse;
module.exports = envParse;
54 changes: 54 additions & 0 deletions src/env-parser.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/* eslint-env mocha */
/* globals describe, it, before, after, beforeEach, afterEach */

import { expect } from 'chai';
import envParser from './env-parser';

describe('env-parser', () => {
beforeEach(() => {
process.env = {
'DATABASE.MONGODB_HOST': 'localhost',
'DATABASE.MONGODB.PORT': '27316',
'REDIS:HASH-ALGO': 'testName',
};
});

it('return type', () => {
expect(() => {
const result = envParser();

expect(result).to.be.an.instanceof(Map, 'Return value must be a Map');
}).not.to.throw();
});

it('keys format', () => {
expect(() => {
envParser().forEach((value, key) => {
expect(key).to.match(/^[A-Za-z\d.]+$/);
});
}).not.to.throw();
});

it('flat keys', () => {
process.env = {
DATABASE_MONGODB_HOST: 'localhost',
'REDIS-HASH-ALGO': 'testName',
};

expect(() => {
envParser({ flatOnly: true }).forEach((value, key) => {
expect(key).to.match(/^[A-Za-z\d.]+$/);
});
}).not.to.throw();
});

it('flat keys - try invalid key', () => {
process.env = {
'REDIS:HASH-ALGO': 'testName',
};

expect(() => {
envParser({ flatOnly: true });
}).to.throw(Error, /Unsupported env field name/);
});
});

0 comments on commit cee0ff6

Please sign in to comment.