Adding syntax prefix parsing to specific types instead of only string var (#4190)

* Adding syntax prefix parsing to specific types instead of only strings env variables

* Update api/src/env.ts

* Update docs/reference/environment-variables.md

* Update docs/reference/environment-variables.md

* Ignore pre-parsed types

Co-authored-by: Rijk van Zanten <rijkvanzanten@me.com>
This commit is contained in:
Juan Carlos Blanco Delgado
2021-02-22 16:36:24 +00:00
committed by GitHub
parent cf261f4eb2
commit 7dee95e8aa
2 changed files with 42 additions and 0 deletions

View File

@@ -12,6 +12,8 @@ import { clone, toString, toNumber } from 'lodash';
import { toArray } from './utils/to-array';
import logger from './logger';
const acceptableEnvTypes = ['string', 'number', 'regex', 'array'];
const defaults: Record<string, any> = {
CONFIG_PATH: path.resolve(process.cwd(), '.env'),
PORT: 8055,
@@ -123,10 +125,39 @@ function getEnv() {
return dotenv.parse(fs.readFileSync(configPath).toString());
}
function getVariableType(variable: string) {
return variable.split(':').slice(0, -1)[0];
}
function getEnvVariableValue(variableValue: string, variableType: string) {
return variableValue.split(`${variableType}:`)[1];
}
function getEnvironmentValueByType(envVariableString: string) {
const variableType = getVariableType(envVariableString);
const envVariableValue = getEnvVariableValue(envVariableString, variableType);
switch (variableType) {
case 'number':
return toNumber(envVariableValue);
case 'array':
return toArray(envVariableValue);
case 'regex':
return new RegExp(envVariableValue);
case 'string':
return envVariableValue;
}
}
function processValues(env: Record<string, any>) {
env = clone(env);
for (const [key, value] of Object.entries(env)) {
if (typeof value === 'string' && acceptableEnvTypes.some((envType) => value.includes(`${envType}:`))) {
env[key] = getEnvironmentValueByType(value);
continue;
}
if (typeMap[key]) {
switch (typeMap[key]) {
case 'number':