Last active
October 1, 2021 04:01
-
-
Save tim-rohrer/87092e2bc16576afabfbd63b0a128d4f to your computer and use it in GitHub Desktop.
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 { config, DotenvConfigOutput, DotenvParseOutput } from "dotenv" | |
import { Err, Ok, Result } from "ts-results"; | |
export class AppConfiguration { | |
private static instance: AppConfiguration = new AppConfiguration() | |
private static requiredEnvVars = [ "GATEWAY_NS", "GOOGLE_API_KEY", "MONGODB_URI", "SECRET_KEY"] | |
private static envs = {} | |
private constructor() { | |
if(AppConfiguration.instance){ | |
throw new Error("Error: Instantiation failed: Use AppConfiguration.getInstance() instead of new."); | |
} | |
AppConfiguration.instance = this; | |
} | |
public static getInstance(): AppConfiguration { | |
return AppConfiguration.instance; | |
} | |
private static confirmRequiredEnvsPresent( | |
resultToCheck: DotenvConfigOutput, | |
): Result<DotenvParseOutput, Array<string>> { | |
const { parsed: envs } = resultToCheck | |
const errorMessages: Array<string> = [] | |
if (envs !== undefined) { | |
this.requiredEnvVars.forEach((envVar) => { | |
if (!Object.prototype.hasOwnProperty.call(envs, envVar)) | |
errorMessages.push(`Missing ${envVar} in .env file`) | |
}) | |
if (errorMessages.length === 0) return Ok(envs) | |
} else errorMessages.push("Apparently no envs were loaded!") | |
return Err(errorMessages) | |
} | |
public static setEnvVars(): void { | |
const result = config() | |
if (!result.error) { | |
const checkEnvsResult = this.confirmRequiredEnvsPresent(result) | |
if (checkEnvsResult.ok) { | |
this.envs = checkEnvsResult.val | |
} else { | |
throw new Error(`Processing envs failed: ${checkEnvsResult.val}`) | |
} | |
} else throw new Error("Problem reading environment variables") | |
} | |
public static getEnvVars(): Record<string, string | number> { | |
return this.envs | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment