All files / libs/config/src index.ts

100% Statements 11/11
75% Branches 3/4
100% Functions 2/2
100% Lines 11/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 302x 2x     2x   2x               2x     2x 2x 2x 2x 2x 2x              
import { z } from 'zod';
import dotenv from 'dotenv';
 
// Load .env once on first import
dotenv.config();
 
const schema = z.object({
  NATS_URL: z.string().default('nats://localhost:4222'),
  PORT: z.string().optional(),
  OTEL_EXPORTER_OTLP_ENDPOINT: z.string().default('http://localhost:4317'),
  LOG_LEVEL: z.string().default('info'),
});
 
function toEnvPrefix(serviceName: string): string {
  return serviceName.replace(/[^a-zA-Z0-9]/g, '_').toUpperCase();
}
 
export function loadConfig(serviceName: string) {
  const env = schema.parse(process.env);
  const prefix = toEnvPrefix(serviceName);
  const specificPortVar = `${prefix}_PORT`;
  const portStr = process.env[specificPortVar] ?? env.PORT;
  return {
    natsUrl: env.NATS_URL,
    port: portStr ? Number(portStr) : undefined,
    otlpEndpoint: env.OTEL_EXPORTER_OTLP_ENDPOINT,
    logLevel: env.LOG_LEVEL,
  };
}