@geektech/backone-utils
全局配置
从环境变量读取强类型配置,启动期 fail-fast 校验。
config 模块从环境变量(或自定义读取源)读取强类型配置,启动期 fail-fast 校验:缺失或非法配置立即抛出 ConfigError,返回的配置对象深冻结(不可变)且类型完整推导。
基本用法
ts
import { defineConfig, v } from '@geektech/backone-utils';
const config = defineConfig(
v.object({
port: v.number({ integer: true, min: 0, max: 65535 }),
jwtSecret: v.string({ minLength: 8 }),
debug: v.boolean(),
}),
{ prefix: 'APP_' }
);
// 读取 APP_PORT / APP_JWT_SECRET / APP_DEBUG
config.port; // number,类型已推导
config.jwtSecret; // string字段名 → 环境变量名
字段名先转 UPPER_SNAKE_CASE 再拼接前缀:jwtSecret → APP_JWT_SECRET;前缀自动大写,缺末尾下划线自动补('app' → 'APP_')。
选项
| 选项 | 说明 |
|---|---|
prefix | 环境变量前缀,如 "APP_" |
source | 读取源,默认 EnvSource(Bun.env + process.env) |
defaults | 缺省值(native 类型),env 未设置时使用 |
自定义读取源
实现 ConfigSource 接口即可接入自定义配置来源(如内存、文件):
ts
import { defineConfig, MemorySource } from '@geektech/backone-utils';
const config = defineConfig(
v.object({ port: v.number() }),
{ source: new MemorySource({ PORT: "8080" }) }
);
config.port; // 8080说明
非法前缀抛 CONFIG_PREFIX_INVALID,校验失败抛 CONFIG_INVALID(携带 issues 列表);配置对象深冻结,值为 JSON 形态数据,无循环引用。