Skip to content

Instantly share code, notes, and snippets.

@janbaykara
Created July 15, 2020 14:53
Show Gist options
  • Save janbaykara/75fee834797411102811280aa4676684 to your computer and use it in GitHub Desktop.
Save janbaykara/75fee834797411102811280aa4676684 to your computer and use it in GitHub Desktop.
Typescript version of Strapi's env mini-library
'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