Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save chill-cod3r/fe866f5d4221fc7574d238d668b98634 to your computer and use it in GitHub Desktop.
Save chill-cod3r/fe866f5d4221fc7574d238d668b98634 to your computer and use it in GitHub Desktop.
Example of strongly typed appconfig validation with simple array of keys
const configKeys = [
"NODE_ENV",
"PORT",
"SECRET1",
"SECRET2",
"SECRET3",
"ASYNC_SECRET",
] as const;
export type AppConfig = {
[key in typeof configKeys[number]]: string;
};
export async function getAppConfig(): Promise<AppConfig> {
/**
* Load any async secrets separately separately
*/
const [secret1, asyncSecret] = await Promise.all([
getMockAsyncSecret(),
getMockAsyncSecret(),
]);
const config: Partial<AppConfig> = {
SECRET1: secret1,
ASYNC_SECRET: asyncSecret,
};
return configKeys.reduce<AppConfig>((appConfig, key) => {
const configValue = process.env[key];
if (appConfig[key]) {
// we already have it from the preloaded secrets
return appConfig;
}
if (!configValue) {
// we should have it and we don't, throw an error
throw new Error(`Missing config value for key: ${key}`);
}
appConfig[key] = configValue;
return appConfig;
}, config as AppConfig);
}
async function getMockAsyncSecret(): Promise<string> {
return new Promise((resolve) =>
setTimeout(() => resolve("mock async secret"), 200)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment