-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenv.ts
More file actions
57 lines (49 loc) · 1.27 KB
/
env.ts
File metadata and controls
57 lines (49 loc) · 1.27 KB
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
import { z } from "zod";
const envSchema = z.object({
DATABASE_URL: z.string().min(1, "DATABASE_URL is required"),
PUBLIC_SERVER_URL: z.string().refine((val) => {
try {
new URL(val);
return true;
} catch {
return false;
}
}, "PUBLIC_SERVER_URL must be a valid URL"),
PUBLIC_GA_ID: z.string().optional(),
PORT: z.coerce.number().int().positive("PORT must be a positive integer"),
});
type EnvSchema = z.infer<typeof envSchema>;
declare module "bun" {
interface Env {
DATABASE_URL: string;
PUBLIC_SERVER_URL: string;
PUBLIC_GA_ID: string;
PORT: number;
}
}
let validatedEnv: EnvSchema | null = null;
export function getValidatedEnv(): EnvSchema {
if (!validatedEnv) {
throw new Error("Environment not validated. Call validateEnv() first.");
}
return validatedEnv;
}
export function validateEnv(): EnvSchema {
try {
validatedEnv = envSchema.parse(Bun.env);
return validatedEnv;
} catch (error) {
if (error instanceof z.ZodError) {
const errorMessages = error.issues
.map((err) => `${err.path.join(".")}: ${err.message}`)
.join("\n");
throw new Error(`Environment validation failed:\n${errorMessages}`);
}
throw error;
}
}
export function initializeEnv() {
return validateEnv();
}
export { envSchema };
export type { EnvSchema };