Skip to content

Commit

Permalink
refactor(get-env-value): rewrite the function
Browse files Browse the repository at this point in the history
  • Loading branch information
AliMD committed Oct 25, 2024
1 parent 98a3897 commit 544e23d
Showing 1 changed file with 28 additions and 11 deletions.
39 changes: 28 additions & 11 deletions packages/get-env-value/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

0 comments on commit 544e23d

Please sign in to comment.