|
| 1 | +import { z } from "zod"; |
| 2 | +import type { Schema, ZodTypeDef } from "zod"; |
| 3 | + |
| 4 | +type PreValidate<ConfigData> = { |
| 5 | + [K in keyof ConfigData]: ConfigData[K] extends object |
| 6 | + ? PreValidate<ConfigData[K]> | undefined |
| 7 | + : ConfigData[K] extends string |
| 8 | + ? string | undefined // use string instead of enum values |
| 9 | + : ConfigData[K] | undefined; |
| 10 | +}; |
| 11 | + |
| 12 | +// Validation |
| 13 | +const validateConfigOrExit = <T, I>( |
| 14 | + schema: Schema<T, ZodTypeDef, I>, |
| 15 | + data: PreValidate<I>, |
| 16 | +): T => { |
| 17 | + try { |
| 18 | + return schema.parse(data); |
| 19 | + } catch (exception: any) { |
| 20 | + if (exception instanceof z.ZodError) { |
| 21 | + console.error("Configuration validation failed. Exit is forced."); |
| 22 | + exception.issues.forEach((issue) => { |
| 23 | + console.error(`\t- issue: ${issue.path.join(".")}: ${issue.message}`); |
| 24 | + }); |
| 25 | + } else { |
| 26 | + console.error(exception); |
| 27 | + } |
| 28 | + process.exit(1); |
| 29 | + } |
| 30 | +}; |
| 31 | + |
| 32 | +// Definitions |
| 33 | +const InstanceSchema = z.object({ |
| 34 | + environment: z.enum(["development", "production", "test"]), |
| 35 | + origin: z.string().url(), |
| 36 | +}); |
| 37 | + |
| 38 | +const ClerkSchema = z.object({ |
| 39 | + publishableKey: z.string(), |
| 40 | + secretKey: z.string(), |
| 41 | +}); |
| 42 | + |
| 43 | +const MainConfigSchema = z |
| 44 | + .object({ |
| 45 | + clerk: ClerkSchema, |
| 46 | + }) |
| 47 | + .merge(InstanceSchema); |
| 48 | + |
| 49 | +export type MainConfig = z.infer<typeof MainConfigSchema>; |
| 50 | + |
| 51 | +const port = process.env.PORT ? Number.parseInt(process.env.PORT, 10) : 5173; |
| 52 | +export const mainConfig: MainConfig = validateConfigOrExit(MainConfigSchema, { |
| 53 | + environment: process.env.NODE_ENV || "development", |
| 54 | + origin: process.env.ORIGIN || `http://localhost:${port}`, |
| 55 | + clerk: { |
| 56 | + publishableKey: process.env.CLERK_PUBLISHABLE_KEY, |
| 57 | + secretKey: process.env.CLERK_SECRET_KEY, |
| 58 | + }, |
| 59 | +}); |
0 commit comments