Skip to content

Instantly share code, notes, and snippets.

@tim-rohrer
Last active October 1, 2021 04:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tim-rohrer/87092e2bc16576afabfbd63b0a128d4f to your computer and use it in GitHub Desktop.
Save tim-rohrer/87092e2bc16576afabfbd63b0a128d4f to your computer and use it in GitHub Desktop.
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