src/config.ts (view raw)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
import { z } from "zod";
const ENVIRONMENT = Bun.env.NODE_ENV || "development";
const IS_PROD = Bun.env.NODE_ENV === "production";
const CONFIG_PATH = `./data/config.${ENVIRONMENT}.json`;
const discordSchema = z.object({
token: z.string(),
app_id: z.string(),
});
const configSchema = z
.object({
discord: discordSchema,
})
.transform((config) => {
return {
...config,
environment: ENVIRONMENT,
isProduction: IS_PROD,
};
});
export type Config = z.infer<typeof configSchema>;
async function loadConfig(): Promise<Config> {
const file = Bun.file(CONFIG_PATH);
if (!(await file.exists())) {
console.error(`[!] couldn't find a config file at ${CONFIG_PATH}`);
process.exit(1);
}
const json = await file.json();
const parsed = configSchema.safeParse(json);
if (parsed.success) return parsed.data;
console.error("[!] failed to parse config:");
const longestPath = Math.max(...parsed.error.issues.map((err) => err.path.join(".").length));
for (const err of parsed.error.issues) {
const path = err.path.join(".");
console.error(` * ${path.padEnd(longestPath)} ${err.message} (${err.code})`);
}
process.exit(1);
}
const config = await loadConfig();
export default config;
|