-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[#51] Implement .env variables retrieving
- Loading branch information
Showing
4 changed files
with
43 additions
and
0 deletions.
There are no files selected for viewing
Empty file.
Empty file.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
/** | ||
* Prefix used for Vite environment variables. | ||
* @constant {string} | ||
*/ | ||
const VITE_ENV_PREFIX = "S_PIPES_"; | ||
|
||
/** | ||
* Object containing environment variables. | ||
* - Includes environment variables from `import.meta.env` that start with `VITE_ENV_PREFIX`. | ||
* - Merges in configuration from `window.__config__`. | ||
* @type {Object<string, string>} | ||
*/ | ||
const ENV = { | ||
...Object.keys(import.meta.env).reduce((accumulator, key) => { | ||
if (key.startsWith(VITE_ENV_PREFIX)) { | ||
const strippedKey = key.replace(VITE_ENV_PREFIX, ""); | ||
accumulator[strippedKey] = import.meta.env[key]; | ||
} | ||
return accumulator; | ||
}, {}), | ||
...window.__config__, | ||
}; | ||
|
||
/** | ||
* Retrieves the value of an environment variable. | ||
* - Returns the value if it exists, otherwise returns the provided default value. | ||
* - Throws an error if the variable is not found and no default value is provided. | ||
* | ||
* @param {string} name - The name of the environment variable to retrieve. | ||
* @param {string} [defaultValue] - Optional default value to return if the environment variable is not found. | ||
* @returns {string} The value of the environment variable or the default value. | ||
* @throws {Error} If the environment variable is not found and no default value is provided. | ||
*/ | ||
export const getEnv = (name, defaultValue) => { | ||
const value = ENV[name] || defaultValue; | ||
|
||
if (value !== undefined) { | ||
return value; | ||
} | ||
|
||
throw new Error(`Missing environment variable: ${name}`); | ||
}; |
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