Created
July 15, 2020 14:53
-
-
Save janbaykara/75fee834797411102811280aa4676684 to your computer and use it in GitHub Desktop.
Typescript version of Strapi's env mini-library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
import { EnvVars } from './types'; | |
// Taken from https://github.com/strapi/strapi/blob/c90e3eb67bf2c235c2fdd1b5607eda6b649d9f10/packages/strapi/lib/core/app-configuration/env-helper.js | |
const _ = require('lodash'); | |
type Translator<T = any> = (key: keyof EnvVars, defaultValue?: T) => T | |
const defaultEnv: Translator = (key, defaultValue) => { | |
return _.has(process.env, key) ? process.env[key] : defaultValue; | |
} | |
const int: Translator<number> = function (key, defaultValue) { | |
if (!_.has(process.env, key)) { | |
return defaultValue; | |
} | |
const value = process.env[key]; | |
return parseInt(value as any, 10); | |
} | |
const float: Translator<number> = (key, defaultValue) => { | |
if (!_.has(process.env, key)) { | |
return defaultValue; | |
} | |
const value = process.env[key]; | |
return parseFloat(value as any); | |
} | |
const bool: Translator<boolean> = (key, defaultValue) => { | |
if (!_.has(process.env, key)) { | |
return defaultValue; | |
} | |
const value = process.env[key]; | |
return value === 'true'; | |
} | |
const json: Translator<{}> = (key, defaultValue) => { | |
if (!_.has(process.env, key)) { | |
return defaultValue; | |
} | |
const value = process.env[key]; | |
try { | |
return JSON.parse(value as any); | |
} catch (error) { | |
throw new Error(`Invalid json environment variable ${key}: ${error.message}`); | |
} | |
} | |
const array: Translator<Array<any>> = (key, defaultValue) => { | |
if (!_.has(process.env, key)) { | |
return defaultValue; | |
} | |
let value = process.env[key].toString(); | |
if (value.startsWith('[') && value.endsWith(']')) { | |
value = value.substring(1, value.length - 1); | |
} | |
return value.split(',').map(v => { | |
return _.trim(_.trim(v, ' '), '"'); | |
}); | |
} | |
const date: Translator<Date> = (key, defaultValue) => { | |
if (!_.has(process.env, key)) { | |
return defaultValue; | |
} | |
const value = process.env[key]; | |
return new Date(value); | |
} | |
const env = Object.assign( | |
defaultEnv, | |
{ | |
int, | |
float, | |
bool, | |
date, | |
json, | |
array | |
} | |
) | |
export default env |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment