Verify env vars with Node.js
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
ARR1 = "value1 value2 value3" | |
ANOTHER = "test" | |
OPTIONAL_EXAMPLE = "optional test" |
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
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