Skip to content

Instantly share code, notes, and snippets.

@Pasi-D
Last active March 23, 2024 20:23
Show Gist options
  • Save Pasi-D/7cef1d2c4dda54c16e3c232fa007cb23 to your computer and use it in GitHub Desktop.
Save Pasi-D/7cef1d2c4dda54c16e3c232fa007cb23 to your computer and use it in GitHub Desktop.
React Native env accessor and version name displayer
/*****************************************************************************************
* Accesses a variable inside of .env file and cache for later usage; throws an error if its not found.
*
* caching the values to improve the performance.
*
* Usage:
*
* import accessEnv from "helpers/accessEnv";
*
* const redirectionHost = accessEnv("MAJOR_VERSION", 1);
****************************************************************************************/
import Config from "react-native-config";
const cache: Record<string, string> = {};
const accessEnv = (key: string, defaultValue?: string | number): any => {
// If the .env variable is not declared
if (![key in Config]) {
if (defaultValue) {
return defaultValue;
}
throw new Error(`${key} not found in .env`);
}
// If returned as undefined
if (Config[key] === undefined) {
if (defaultValue) {
return defaultValue;
}
throw new Error(`${key} not found in .env`);
}
if (cache[key]) {
return cache[key];
}
cache[key] = Config[key];
return Config[key];
};
export default accessEnv;
import accessEnv from "helpers/accessEnv";
/**
* Checks if the entity is undefined or not
* @param state - Target entity
*/
export const isUndefined = (state: any): boolean => typeof state === "undefined";
/**
* Returns version name of the app
*/
export const getAppVersionName = (): string => {
let version = `v.${accessEnv("MAJOR_VERSION")}.${accessEnv(
"MINOR_VERSION",
)}.${accessEnv("PATCH_VERSION")}`;
if (!isUndefined(accessEnv("PRE_RELEASE", undefined))) {
version = version.concat(`-${accessEnv("PRE_RELEASE")}`);
}
return version;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment