Created
October 18, 2021 00:59
-
-
Save tim-rohrer/0ebc04587d37578679302a789132269f 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" | |
import Logger from "./logger" | |
export class AppConfiguration { | |
private static instance: AppConfiguration = new AppConfiguration() | |
private static requiredEnvVars: ReadonlyArray<string> = [ | |
"GATEWAY_NS", | |
"GOOGLE_API_KEY", | |
"GOOGLE_USER_EMAIL", | |
"GOOGLE_SERVICE_CLIENT", | |
"GOOGLE_EMAIL_PRIVATE_KEY", | |
"MONGODB_URI", | |
] | |
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 { | |
let result | |
if (process.env.NODE_ENV === ("development" || "dev")) { | |
result = config() | |
} else result = process.env | |
Logger.debug( | |
`AppConfiguration.setEnvVars config: ${JSON.stringify(result)}`, | |
) | |
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, unknown> { | |
return this.envs | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment