Last active
March 23, 2024 20:23
-
-
Save Pasi-D/7cef1d2c4dda54c16e3c232fa007cb23 to your computer and use it in GitHub Desktop.
React Native env accessor and version name displayer
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
/***************************************************************************************** | |
* 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; |
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
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