Skip to content

Commit

Permalink
[#51] Implement .env variables retrieving
Browse files Browse the repository at this point in the history
  • Loading branch information
palagdan committed Aug 29, 2024
1 parent 3585dea commit b7998f8
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 0 deletions.
Empty file added .env.development
Empty file.
Empty file added .env.production
Empty file.
42 changes: 42 additions & 0 deletions src/config/env.js
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}`);
};
1 change: 1 addition & 0 deletions vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export default defineConfig({
define: {
"process.env": process.env,
},
envPrefix: "S_PIPES_",
resolve: {
mainFields: [],
},
Expand Down

0 comments on commit b7998f8

Please sign in to comment.