Skip to content

Instantly share code, notes, and snippets.

@devgioele
Last active May 12, 2022 14:52
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save devgioele/e3b23ec7458cf10a8e34d9e5befd9c45 to your computer and use it in GitHub Desktop.
Verify env vars with Node.js
ARR1 = "value1 value2 value3"
ANOTHER = "test"
OPTIONAL_EXAMPLE = "optional test"
export enum RequiredEnvVar {
ARR1 = 'ARR1',
ANOTHER = 'ANOTHER'
}
export enum OptionalEnvVar {
OPTIONAL_EXAMPLE = 'OPTIONAL_EXAMPLE'
}
export type EnvVar = RequiredEnvVar | OptionalEnvVar
export const loadOptionalEnvVar = (key: EnvVar): string | undefined =>
process.env[key]
export const loadEnvVar = (key: RequiredEnvVar): string =>
loadOptionalEnvVar(key) as string
export const loadOptionalEnvVarArray = (
key: EnvVar,
separator = ' '
): string[] | undefined => {
const env = process.env[key]
return env?.split(separator)
}
export const loadEnvArray = (key: RequiredEnvVar, separator = ' '): string[] =>
loadOptionalEnvVarArray(key, separator) as string[]
/** Verifies that all required environment variables exist. */
export const envVarsAreCorrect = (): boolean => {
return (
Object.values(RequiredEnvVar).every(key => !!loadEnvVar(key)) &&
Object.values(OptionalEnvVar).every(key => !!loadOptionalEnvVar(key))
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment