all repos — discord-utils @ 492186c2891cfcdb565eed0850083c9d6f577d4b

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
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
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 gameSchema = z
	.object({
		name: z.string(),
		universeId: z.string(),
	})
	.transform((game) => {
		const initials = game.name
			.split(" ")
			.map((word) => word[0])
			.join("");

		return {
			...game,
			id: initials.toLowerCase(),
		};
	});

const gamesSchema = z.array(gameSchema);

const configSchema = z
	.object({
		discord: discordSchema,
		games: gamesSchema,
		roblox: z.object({
			cookie: z.string(),
		}),
	})
	.transform((config) => {
		return {
			...config,
			environment: ENVIRONMENT,
			isProduction: IS_PROD,
		};
	});

// --- types ------------------------------------------------------------------
export type Config = z.infer<typeof configSchema>;
export type Game = z.infer<typeof gameSchema>;

// ----------------------------------------------------------------------------
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;