From ca08ed9294c323aef02f7761e30b4dad7c06883e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=20Jurmanovi=C4=87?= Date: Wed, 12 Aug 2026 20:51:03 +0200 Subject: [PATCH] Add core env loader --- src/core/config/env.ts | 9 +++++++++ test/core/config/env.test.ts | 19 +++++++++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 src/core/config/env.ts create mode 100644 test/core/config/env.test.ts diff --git a/src/core/config/env.ts b/src/core/config/env.ts new file mode 100644 index 0000000..ab970fa --- /dev/null +++ b/src/core/config/env.ts @@ -0,0 +1,9 @@ +import type { ZodSchema } from 'zod'; + +export function loadEnv(schema: ZodSchema, source: NodeJS.ProcessEnv = process.env): T { + const result = schema.safeParse(source); + if (!result.success) { + throw new Error(`Invalid environment configuration: ${result.error.message}`); + } + return result.data; +} diff --git a/test/core/config/env.test.ts b/test/core/config/env.test.ts new file mode 100644 index 0000000..32a97cd --- /dev/null +++ b/test/core/config/env.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from 'vitest'; +import { z } from 'zod'; +import { loadEnv } from '../../../src/core/config/env'; + +describe('loadEnv', () => { + const schema = z.object({ + FOO: z.string(), + COUNT: z.coerce.number().default(5), + }); + + it('parses matching env vars into a typed object', () => { + const result = loadEnv(schema, { FOO: 'bar', COUNT: '10' }); + expect(result).toEqual({ FOO: 'bar', COUNT: 10 }); + }); + + it('throws a descriptive error when required vars are missing', () => { + expect(() => loadEnv(schema, {})).toThrow(/Invalid environment configuration/); + }); +});