# @grest-ts/config 中文文档

规范地址：https://npmcn.com/package/%40grest-ts/config/

版本：0\.0\.101
npm 元数据更新时间：2026-11-02T15:34:29.349Z
中文译文更新时间：2026-11-17T19:27:55.542Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40grest-ts/config
原文对照：https://npmcn.com/package/%40grest-ts/config/?lang=original
项目主页：https://grest-ts.com/packages/config
源码仓库：https://github.com/grest-ts/grest-ts

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：175 kB，105 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- Node.js 要求：\>=24
- 运行依赖：0 个
- 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
- 首次发布：2026-02-24T10:54:21.578Z
- 最新版本发布：2026-11-02T15:34:29.149Z
- 近 30 天下载量：4472（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：84（近 12 个月 84 个）

## 中文简介

Grest 框架的配置管理 - 资源、秘密和设置

## 安装

```sh
npm install @grest-ts/config
```

也可以使用：`pnpm add @grest-ts/config`、`yarn add @grest-ts/config`、`bun add @grest-ts/config`

## README

> 部分 [灰尘](https://github.com/grest-ts/grest-ts) 框架. [文档](https://github.com/grest-ts/grest-ts#readme) | [所有软件包](https://github.com/grest-ts/grest-ts#package-reference)

# @ grest-ts/ 配置

Grest Framework的型式安全配置管理.

## 特征

-   具有验证特性的类型安全配置密钥
-   多键类型( 设置、 秘密、 资源)
-   可插件存储后端( 文件、 环境、 远程)
-   有监视器的运行时配置更新
-   集中配置定义
-   配置值被验证 !

## 图案

-   密钥是静态定义的, 但值在运行时从同步上下文解析
-   不同的密钥类型( setting, Secret, Resource) 可以使用不同的存储后端( 策略模式)
-   支持监视运行时间配置变化(观察员模式)

## 开始

### 1\. 定义您的配置

```typescript
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\. 为发展提供地方价值

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

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

`createLocalConfig` 是一个编译时间帮助器——它对照您的配置定义对数值进行键入检查。 需要资源和秘密;设置可能被忽略,然后使用默认设置.

### 3\. 在你的运行时间拨接它

```typescript
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({ ... }))
```

何时 `localConfig` 传递给构造器,存储自动交换 `GGConfigStoreLocal` 生产之外——因此,你的真货店(AWS,文件等)只有在使用时才会使用 `NODE_ENV=production`。 。 。 .

### 4\. 使用该工具

```typescript
// 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
```

## 密钥类型

| 类型 | 构造器 | 读取方法 | 使用大小写 |
| --- | --- | --- | --- |
| **GGSetting (英语)** | `(name, schema, default, description)` | `.get()` | 一般配置(端口、旗帜) |
| **GGSecret (英语)** | `(name, schema, description)` | `.reveal()` | 敏感数据( API 密钥、 密码) |
| **GGRE 源码** | `(name, schema, description)` | `.get()` | 基础设施(URL、主机、路径) |

设置有默认值 。 秘密和资源不能——它们的价值观必须来自商店.

## 验证

所有密钥都需要一个 `@grest-ts/schema` 验证器。 从商店装入值时验证值 . 启动时无效的配置使服务无法启动 。 运行时重装时无效的配置被拒绝, 错误被提出—— 先前的有效值仍然有效 . 商店在失败前验证其所有密钥, 因此错误名称为每个缺失或无效的密钥 。 错误永远不会包括失败的值,因为它们可能是秘密.

在生产中,一个商店的初始负载失效 `GGConfigLoadError` (配置无法读取或无效)不会失败启动:每10秒重试一次,每次失败都到 `GGConfigLocator.onStartupError` (默认: 关键日志). 配置首先开始, 所以数据库, HTTP 和工作等它加载; 在此期间没有为交通服务 。 经过10分钟的启动后放弃并失败了最后一个错误. 任何其它出错一次启动失败,外部生产启动总是立即失败.

```typescript
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
```

```typescript
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')
```

### 在不开始的情况下检查配置文档

定义是代码,因此它可以描述和检查部署的配置文档(JSON文件或密件管理器存储负载)在任何运行前:

```typescript
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` 解决路径完全像商店,所以 `ok: true` 表示装入此文档的商店将启动 。 需要的键左边 `null` 计数为缺失 -- `check(template())` 列出要填写的内容. `unknown` 列出没有读取的密钥路径( 存在或拼错密钥)。 过 `{types: [GGSecret, GGResource]}` 将其中任何一个范围扩大到一号店服务的关键类型.

偏爱 `GGResource` 一个以上 `GGSetting` 默认任何部署特定(URL,域名,桶名) : 资源没有默认,所以部署会忘记它在启动时失败,而不是默默地使用另一个环境的值.

## 存储后端

`GGConfigLocator` 映射要存储的密钥类型。 每个密钥类型在开始前必须有一个商店注册.

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

多个密钥类型可以共享一个存储 :

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

### GGConfigStore 文件( G)

从 JSON 文件读取值 。 监视文件目录并自动重载( 100ms debounce) , 因此既可以在原地写, 也可以在原地写( 然后写临时文件) `rename` 在目标上空)被取出.

-   **初始负载** 大声失败: 缺少、 空、 无法解析或无效的文件 `start()` 掷出.
-   **重新装入** 是全或无:每个密钥在任何值变化前都会被验证。 如果任何失败( 无法读取文件、 空文件、 糟糕的 JSON 、 计划失败) , 商店会保留其最后的好值, 并将错误报告给 `GGConfigLocator.onReloadError` (默认: 关键日志; 覆盖到提醒路径). 一个被删除的文件同样被报告;回写它触发了重装.
-   **已更改密钥** 以信息级别登录,有新旧价值; a `GGSecret` 仅记录其名称.
-   **观察者** (单位:千美元)`key.watch()`)每重新装入一次起火,仅用于已验证值已改变(深度等同)的密钥. 一个偷看的人 `onNotifyError`;如果投出(默认),则误差将传给 `onReloadError` 而不是无所顾忌地逃跑.

关键路径 `/app/server/port` 地图到 `app.server.port` 在JSON中:

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

### GGConfigStore 本地服务器

类型安全开发商店. 拒绝在 `NODE_ENV=production`。 。 。 .

```typescript
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 数据存储系统

读取环境变量,用于部署时将其配置为嵌入的流程(系统化) `EnvironmentFile`,容器)。 密钥 `/app/db/host` 读取 `{prefix}DB_HOST`: 配置根被丢弃 `/` 变成 `_`。一个未设置或空变量返回到密钥的默认值。 作为平面字符串的图案拒绝的值是 JSON 被分解的,所以数字,布尔和对象都起作用了. 数值一经起读.

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

### GGConfigStoreAwsSecrets 管理器

见 [@ grest-ts/ 配置锯](https://npmcn.com/package/%40grest-ts/config-aws/README.md)。 。 。 .

## 测试

配置在测试之间自动恢复——不需要人工清理. 当测试修改配置时 `t.config.update()`,测试 kit 记录哪些密钥被更改,并在测试完成后返回.

```typescript
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
    });
});
```

配置设置于 `beforeAll` 或由框架钩(如:. `GGTest.with().clone()`)被保留——只恢复在个别测试过程中作出的修改. 这跟窝里也有关系 `describe` 块: 每个瞄准镜的 `beforeAll` 在其 `afterAll`,所以兄妹描述 不见相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相.

## 进一步阅读

-   [扩展](https://npmcn.com/package/%40grest-ts/config/README-extending.md) - 如何添加自定义密钥类型和存储

## 常见问题

### @grest-ts/config 是什么？

Grest 框架的配置管理 - 资源、秘密和设置

### 如何安装 @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 和提交记录判断。

