mirror of
https://github.com/FJurmanovic/sugarr.git
synced 2026-11-11 15:51:09 +00:00
Add core env loader
This commit is contained in:
9
src/core/config/env.ts
Normal file
9
src/core/config/env.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import type { ZodSchema } from 'zod';
|
||||||
|
|
||||||
|
export function loadEnv<T>(schema: ZodSchema<T>, 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;
|
||||||
|
}
|
||||||
19
test/core/config/env.test.ts
Normal file
19
test/core/config/env.test.ts
Normal file
@@ -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/);
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user