| 1 | import type { ZodObject, ZodRawShape } from "zod"; |
| 2 | |
| 3 | interface EnvOptions { |
| 4 | source?: NodeJS.ProcessEnv; |
| 5 | serviceName?: string; |
| 6 | } |
| 7 | |
| 8 | type SchemaOutput<TSchema extends ZodRawShape> = ZodObject<TSchema>["_output"]; |
| 9 | |
| 10 | export const createEnv = <TSchema extends ZodRawShape>( |
| 11 | schema: ZodObject<TSchema>, |
| 12 | options: EnvOptions = {} |
| 13 | ): SchemaOutput<TSchema> => { |
| 14 | const { source = process.env, serviceName = "service" } = options; |
| 15 | |
| 16 | const parsed = schema.safeParse(source); |
| 17 | |
| 18 | if (!parsed.success) { |
| 19 | const formatedErrors = parsed.error.format(); |
| 20 | throw new Error( |
| 21 | `[${serviceName}] Environment variable validation failed: ${JSON.stringify(formatedErrors)}` |
| 22 | ); |
| 23 | } |
| 24 | |
| 25 | return parsed.data; |
| 26 | }; |
| 27 | |
| 28 | export type EnvSchema<TShape extends ZodRawShape> = ZodObject<TShape>; |