From 544e23d2a4b930438901f3c17716a079235dd8d6 Mon Sep 17 00:00:00 2001 From: Ali Mihandoost Date: Fri, 25 Oct 2024 16:02:47 +0330 Subject: [PATCH] refactor(get-env-value): rewrite the function --- packages/get-env-value/src/main.ts | 39 +++++++++++++++++++++--------- 1 file changed, 28 insertions(+), 11 deletions(-) diff --git a/packages/get-env-value/src/main.ts b/packages/get-env-value/src/main.ts index cdc82076..967ccad5 100644 --- a/packages/get-env-value/src/main.ts +++ b/packages/get-env-value/src/main.ts @@ -3,25 +3,42 @@ import {platformInfo} from '@alwatr/platform-info'; __dev_mode__: packageTracer.add(__package_name__, __package_version__); -interface GetEnvValueParams { +/** + * Parameters for retrieving an environment variable value. + */ +export type GetEnvValueParams = { + /** + * The name of the environment variable. + */ name: string; + + /** + * The default value to use if the environment variable is not set. + * If not provided, the environment variable is required and an error will be thrown if it is not set. + * Except in development mode, where the development value will be used instead if provided. + */ defaultValue?: string; + + /** + * The value to use in a development environment. + * It will be overwrite the default value in development mode and completely ignored in production mode. + */ developmentValue?: string; } -export function getEnvValue(params: GetEnvValueParams): string { - if (platformInfo.development === true) { - const value = params.developmentValue ?? params.defaultValue; - if (value === undefined) { - throw new Error(`Set default value or development value for ${params.name} while you are developing.`); - } +export function getEnvValue(option: GetEnvValueParams): string { + let value = process.env[option.name]; + if (value === '') value = undefined; // empty string is considered as undefined in environment variables - return value; + value ??= option.defaultValue; + + if (platformInfo.development === true) { + value ??= option.developmentValue; } - if (process.env[params.name] === undefined || process.env[params.name] === '') { - throw new Error(`${params.name} is a required ENV key in production.`); + if (value === undefined) { + throw new Error(`Environment variable "${option.name}" is required.`); } - return process.env[params.name]!; + return value; }