@clipboard-health/config
Type-safe static configuration management: a pure function to resolve, validate against a Zod schema, and freeze configuration values.
Table of contents
Install
npm install @clipboard-health/config
Usage
Type-safe configuration
The TypeDoc comment for the createConfig
function:
import { deepFreeze } from "@clipboard-health/util-ts";
import dotenv from "dotenv";
import { fromZodError } from "zod-validation-error";
import { resolve } from "./internal/resolver";
import { type ConfigParams } from "./types";
dotenv.config();
export function createConfig<
const SchemaT extends Record<string, unknown>,
const EnvironmentT extends readonly string[],
>(params: Readonly<ConfigParams<SchemaT, EnvironmentT>>): Readonly<SchemaT> {
const { config, environment, schema } = params;
const { current } = environment;
const result = schema.safeParse(resolve({ config, environment: current, path: [], schema }));
if (!result.success) {
throw new Error(`Configuration validation failed: ${fromZodError(result.error).toString()}`, {
cause: result.error,
});
}
return deepFreeze(result.data);
}
A usage example:
import { ok } from "node:assert/strict";
import { createConfig } from "@clipboard-health/config";
import { z } from "zod";
const allowed = ["local", "development", "production"] as const;
type Allowed = (typeof allowed)[number];
function createEnvironmentConfig(current: Allowed) {
return createConfig({
config: {
baseUrl: {
defaultValue: "http://localhost:3000",
description: "Base URL for API requests",
overrides: {
development: "https://dev.example.com",
production: "https://api.example.com",
},
},
database: {
port: {
defaultValue: 5432,
description: "Database port",
},
},
},
environment: { allowed, current },
schema: z.object({
baseUrl: z.string().url(),
database: z.object({
port: z.coerce.number().min(1024).max(65_535),
}),
}),
});
}
{
const config = createEnvironmentConfig("local");
ok(config.baseUrl === "http://localhost:3000");
ok(config.database.port === 5432);
}
{
const config = createEnvironmentConfig("development");
ok(config.baseUrl === "https://dev.example.com");
ok(config.database.port === 5432);
}
const original = { ...process.env };
try {
process.env["BASE_URL"] = "https://staging.example.com";
process.env["DATABASE_PORT"] = "54320";
const config = createEnvironmentConfig("local");
ok(config.baseUrl === "https://staging.example.com");
ok(config.database.port === 54_320);
} finally {
process.env = { ...original };
}
Local development commands
See package.json
scripts
for a list of commands.