@grest-ts/config

中文文档
0.0.101发布于 2026/11/02MITTypeScriptES Module零依赖近 30 天下载 4472

Configuration management for Grest Framework - resources, secrets, and settings

原始使用文档
文档目录17 节
  1. Features
  2. Pattern
  3. Getting Started
  4. 1. Define your configuration
  5. 2. Provide local values for development
  6. 3. Wire it up in your runtime
  7. 4. Use it
  8. Key Types
  9. Validation
  10. Checking a config document without starting
  11. Storage Backends
  12. GGConfigStoreFile
  13. GGConfigStoreLocal
  14. GGConfigStoreEnv
  15. GGConfigStoreAwsSecretsManager
  16. Testing
  17. Further Reading

Part of the grest-ts framework. Documentation | All packages

@grest-ts/config

Type-safe configuration management for Grest Framework.

Features

  • Type-safe configuration keys with validation
  • Multiple key types (Settings, Secrets, Resources)
  • Pluggable storage backends (file, environment, remote)
  • Runtime configuration updates with watchers
  • Centralized configuration definitions
  • Config values are validated!

Pattern

  • Keys are defined statically, but values are resolved at runtime from async context
  • Different key types (Setting, Secret, Resource) can use different storage backends (Strategy pattern)
  • Supports watching for runtime configuration changes (Observer pattern)

Getting Started

1. Define your configuration

import {GGConfig, GGSetting, GGSecret, GGResource} from "@grest-ts/config"
import {IsString, IsPosInt, IsBoolean} from "@grest-ts/schema"

export const AppConfig = GGConfig.define('/app/', () => ({
    server: {
        port: new GGSetting('server/port', IsPosInt, 3000, 'HTTP server port'),
        debug: new GGSetting('debug', IsBoolean, false, 'Enable debug mode'),
    },
    database: {
        host: new GGResource('db/host', IsString, 'Database host'),
        password: new GGSecret('db/password', IsString, 'Database password'),
    }
}));

2. Provide local values for development

import {createLocalConfig} from "@grest-ts/config"

export const localConfig = createLocalConfig(AppConfig, {
    database: {
        host: "localhost:5432",
        password: "root"
    }
});

createLocalConfig is a compile-time helper — it type-checks the values against your config definition. Resources and secrets are required; settings may be left out, and then use their default.

3. Wire it up in your runtime

import {GGConfigLocator, GGConfigStoreFile} from "@grest-ts/config"

new GGConfigLocator(AppConfig, localConfig)
    .add(GGSetting, new GGConfigStoreFile('./config/settings.json', import.meta.url))
    .add([GGSecret, GGResource], new GGConfigStoreAwsSecretsManager({ ... }))

When localConfig is passed to the constructor, stores are automatically swapped for GGConfigStoreLocal outside of production — so your real stores (AWS, files, etc.) are only used when NODE_ENV=production.

4. Use it

// Settings - .get()
const port = AppConfig.server.port.get();
const debug = AppConfig.server.debug.get();

// Secrets - .reveal() to make intent explicit
const dbPassword = AppConfig.database.password.reveal();

// Resources - .get()
const dbHost = AppConfig.database.host.get();

// Watch for runtime changes
const unwatch = AppConfig.server.port.watch((newPort) => {
    console.log('Port changed to:', newPort);
});
unwatch(); // stop watching

Key Types

TypeConstructorRead methodUse Case
GGSetting(name, schema, default, description).get()General configuration (ports, flags)
GGSecret(name, schema, description).reveal()Sensitive data (API keys, passwords)
GGResource(name, schema, description).get()Infrastructure (URLs, hosts, paths)

Settings have a default value. Secrets and resources do not — their values must come from a store.

Validation

All keys require a @grest-ts/schema validator. Values are validated when loaded from a store. Invalid config at startup prevents the service from starting. Invalid config during a runtime reload is rejected and an error is raised — the previous valid value remains in effect. A store validates all its keys before failing, so the error names every missing or invalid key. Errors never include the failing values, since they may be secrets.

In production a store whose initial load fails with a GGConfigLoadError (config unreadable or invalid) doesn't fail startup: it is retried every 10 seconds, and each failure goes to GGConfigLocator.onStartupError (default: critical log). Config starts first, so database, HTTP and jobs wait until it loads; nothing serves traffic in the meantime. After 10 minutes startup gives up and fails with the last error. Any other error fails startup at once, and outside production startup always fails immediately.

new GGConfigLocator(AppConfig, localConfig, {startupRetryMs: 5_000, startupTimeoutMs: 120_000})
new GGConfigLocator(AppConfig, localConfig, {startupRetryMs: 0}) // e.g. a one-shot job: fail at once
import {IsString, IsPosInt, IsBoolean, IsLiteral} from "@grest-ts/schema"

port: new GGSetting('port', IsPosInt, 8080, 'Server port')
name: new GGSetting('name', IsString, 'default', 'App name')
env:  new GGSetting('env', IsLiteral('dev', 'staging', 'prod'), 'dev', 'Environment')

Checking a config document without starting

The definition is code, so it can describe and check a deployment's config document (the JSON a file or Secrets Manager store loads) before anything runs:

GGConfig.describe(AppConfig)            // [{name, type, required, default, description, definedAt}, ...]
GGConfig.template(AppConfig)            // {app: {db: {password: null}, ...}} — required keys as null
GGConfig.check(AppConfig, documentJson) // {missing, invalid, defaulted, unknown, ok}

check resolves paths exactly like the stores, so ok: true means a store loading this document would start. A required key left null counts as missing — check(template()) lists what is still to fill in. unknown lists paths no key reads (stale or misspelled keys). Pass {types: [GGSecret, GGResource]} to scope any of them to the key types one store serves.

Prefer GGResource over a GGSetting default for anything deployment-specific (URLs, domains, bucket names): a resource has no default, so a deployment that forgets it fails at startup instead of silently using another environment's value.

Storage Backends

GGConfigLocator maps key types to stores. Each key type must have a store registered before start.

new GGConfigLocator(AppConfig)
    .add(GGSetting, new GGConfigStoreFile("./config/settings.json", import.meta.url))
    .add(GGResource, new GGConfigStoreFile("./config/resources.json", import.meta.url))

Multiple key types can share a store:

new GGConfigLocator(AppConfig)
    .add([GGSetting, GGResource], new GGConfigStoreFile("./config/config.json", import.meta.url))

GGConfigStoreFile

Reads values from a JSON file. Watches the file's directory and automatically reloads (100ms debounce), so both in-place writes and atomic writes (write a temp file, then rename it over the target) are picked up.

  • Initial load fails loudly: a missing, empty, unparsable or invalid file makes start() throw.
  • Reloads are all-or-nothing: every key is validated before any value changes. If anything fails (unreadable file, empty file, bad JSON, schema failure), the store keeps its last good values and reports the error to GGConfigLocator.onReloadError (default: critical log; override it to route to alerting). A deleted file is reported the same way; writing it back triggers a reload.
  • Changed keys are logged at info level with old and new value; a GGSecret logs only its name.
  • Watchers (key.watch()) fire once per reload, only for keys whose validated value changed (deep equality). A watcher that throws goes to onNotifyError; if that throws (the default), the error is passed to onReloadError instead of escaping as an unhandled rejection.

The key path /app/server/port maps to app.server.port in JSON:

{
    "app": {
        "server": {
            "port": 8080
        },
        "debug": true
    }
}

GGConfigStoreLocal

Type-safe development store. Refuses to start when NODE_ENV=production.

import {createLocalConfig, GGConfigStoreLocal} from "@grest-ts/config"

const localConfig = createLocalConfig(AppConfig, {
    database: {
        host: "localhost:5432",
        password: "root"
    }
});

new GGConfigLocator(AppConfig)
    .add([GGResource, GGSecret], new GGConfigStoreLocal(AppConfig, localConfig))
    .add(GGSetting, new GGConfigStoreFile('./config/settings.json', import.meta.url))

GGConfigStoreEnv

Reads environment variables, for processes whose deployment hands them config as env (systemd EnvironmentFile, containers). Key /app/db/host reads {prefix}DB_HOST: the config root is dropped and / becomes _. An unset or empty variable falls back to the key's default. A value the schema rejects as a plain string is JSON-parsed, so numbers, booleans and objects work. Values are read once at start.

new GGConfigLocator(AppConfig)
    .add([GGSetting, GGResource], new GGConfigStoreEnv({prefix: "MYAPP_"}))

GGConfigStoreAwsSecretsManager

See @grest-ts/config-aws.

Testing

Config is automatically restored between tests — no manual cleanup needed. When a test modifies config via t.config.update(), the testkit records which keys were changed and reverts them after the test completes.

describe("my tests", () => {
    const t = GGTest.startWorker(MyRuntime);

    test('modify config for this test', async () => {
        await t.config.update(AppConfig.server.port, 9999);
        // ... test with modified config
    });

    test('next test sees original config', async () => {
        const port = await t.config.get(AppConfig.server.port);
        expect(port).toBe(3000); // automatically restored
    });
});

Config set in beforeAll or by framework hooks (e.g. GGTest.with().clone()) is preserved — only changes made during individual tests are reverted. This also works with nested describe blocks: each scope's beforeAll overrides are reverted in its afterAll, so sibling describes don't see each other's config.

Further Reading

  • Extending - How to add custom key types and stores

版本与发布记录

@grest-ts/config 共发布 84 个版本,首次发布于 2026/02/24;过去 12 个月发布了 84 个版本。

版本发布日期距今
0.0.101latest2026/11/0215 天前
0.0.1002026/10/3018 天前
0.0.992026/10/3019 天前
0.0.982026/10/2821 天前
0.0.972026/10/2721 天前
0.0.962026/10/2721 天前

关于 @grest-ts/config 的常见问题

@grest-ts/config 是什么?

Configuration management for Grest Framework - resources, secrets, and settings

如何安装 @grest-ts/config?

在项目目录运行 npm install @grest-ts/config,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@grest-ts/common(0.0.101)、@grest-ts/logger(0.0.101)、@grest-ts/schema(0.0.101)、@grest-ts/locator(0.0.101)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@grest-ts/config 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@grest-ts/config 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@grest-ts/config 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=24。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@grest-ts/config 可以商用吗?

@grest-ts/config 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@grest-ts/config 的下载量有多少?

根据 npm 官方下载统计,@grest-ts/config 在 2026/10/17 – 2026/11/15 这 30 天内被下载 4,472 次,日均约 149 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@grest-ts/config 还在维护吗?

最新版本 0.0.101 发布于 2026/11/02(15 天前);至今共发布 84 个版本,其中过去 12 个月发布了 84 个;首次发布于 2026/02/24。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。