diff --git a/src/env-parser.js b/src/env-parser.js new file mode 100644 index 0000000..37cd844 --- /dev/null +++ b/src/env-parser.js @@ -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.} + */ +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; diff --git a/src/env-parser.test.js b/src/env-parser.test.js new file mode 100644 index 0000000..9e4805e --- /dev/null +++ b/src/env-parser.test.js @@ -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/); + }); +});