schema-dsl 2.0.0 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +130 -113
- package/LICENSE +21 -21
- package/README.md +628 -628
- package/dist/{DslBuilder-DkLaOo9Q.d.ts → DslBuilder-BIgQOAXp.d.ts} +2 -0
- package/dist/{DslBuilder-DQDN0ZxZ.d.cts → DslBuilder-CjHTucNQ.d.cts} +2 -0
- package/dist/{Validator-hFWKGxir.d.ts → Validator-CllRdrY0.d.ts} +1 -1
- package/dist/{Validator-C7GsVQOH.d.cts → Validator-D6okG9tr.d.cts} +1 -1
- package/dist/index.cjs +75 -29
- package/dist/index.d.cts +10 -4
- package/dist/index.d.ts +10 -4
- package/dist/index.js +75 -29
- package/dist/plugins/custom-format.cjs +33 -17
- package/dist/plugins/custom-format.d.cts +1 -1
- package/dist/plugins/custom-format.d.ts +1 -1
- package/dist/plugins/custom-format.js +33 -17
- package/dist/plugins/custom-type-example.cjs +33 -17
- package/dist/plugins/custom-type-example.d.cts +1 -1
- package/dist/plugins/custom-type-example.d.ts +1 -1
- package/dist/plugins/custom-type-example.js +33 -17
- package/dist/plugins/custom-validator.cjs +0 -2
- package/dist/plugins/custom-validator.d.cts +1 -1
- package/dist/plugins/custom-validator.d.ts +1 -1
- package/dist/plugins/custom-validator.js +0 -2
- package/docs/FEATURE-INDEX.md +553 -553
- package/docs/add-custom-locale.md +496 -496
- package/docs/add-keyword.md +24 -24
- package/docs/api-reference.md +1047 -1047
- package/docs/api.md +13 -13
- package/docs/best-practices-project-structure.md +417 -417
- package/docs/best-practices.md +712 -712
- package/docs/cache-manager.md +344 -344
- package/docs/compile.md +45 -45
- package/docs/conditional-api.md +1307 -1307
- package/docs/custom-extensions-guide.md +339 -339
- package/docs/design-philosophy.md +606 -606
- package/docs/doc-index.md +324 -324
- package/docs/dsl-syntax.md +714 -714
- package/docs/dynamic-locale.md +608 -608
- package/docs/enum.md +482 -482
- package/docs/error-handling.md +1975 -1975
- package/docs/export-guide.md +501 -501
- package/docs/export-limitations.md +567 -567
- package/docs/faq.md +596 -596
- package/docs/frontend-i18n-guide.md +307 -307
- package/docs/i18n-user-guide.md +487 -487
- package/docs/i18n.md +476 -476
- package/docs/index.md +48 -48
- package/docs/json-schema-basics.md +40 -40
- package/docs/label-vs-description.md +271 -271
- package/docs/markdown-exporter.md +406 -406
- package/docs/mongodb-exporter.md +302 -302
- package/docs/multi-language.md +26 -26
- package/docs/multi-type-support.md +322 -322
- package/docs/mysql-exporter.md +280 -280
- package/docs/number-operators.md +449 -449
- package/docs/optional-marker-guide.md +326 -326
- package/docs/performance-guide.md +49 -49
- package/docs/plugin-system.md +381 -381
- package/docs/plugin-type-registration.md +34 -34
- package/docs/postgresql-exporter.md +311 -311
- package/docs/public/favicon.svg +4 -4
- package/docs/quick-start.md +435 -435
- package/docs/runtime-locale-support.md +532 -532
- package/docs/schema-helper.md +345 -345
- package/docs/schema-utils-advanced-issues.md +23 -23
- package/docs/schema-utils-best-practices.md +20 -20
- package/docs/schema-utils-chaining.md +150 -150
- package/docs/schema-utils.md +524 -524
- package/docs/security-checklist.md +20 -20
- package/docs/string-extensions.md +488 -488
- package/docs/troubleshooting.md +486 -486
- package/docs/type-converter.md +310 -310
- package/docs/type-reference.md +242 -242
- package/docs/typescript-guide.md +584 -584
- package/docs/union-type-guide.md +157 -157
- package/docs/union-types.md +284 -284
- package/docs/validate-async.md +491 -491
- package/docs/validate-batch.md +49 -49
- package/docs/validate-dsl-object-support.md +578 -578
- package/docs/validate.md +506 -506
- package/docs/validation-guide.md +502 -502
- package/docs/validator.md +39 -39
- package/package.json +131 -131
- package/plugins/custom-format.cjs +8 -8
- package/plugins/custom-type-example.cjs +8 -8
- package/plugins/custom-validator.cjs +8 -8
- package/src/adapters/DslAdapter.ts +111 -111
- package/src/adapters/index.ts +1 -1
- package/src/config/constants.ts +83 -83
- package/src/config/index.ts +2 -2
- package/src/config/patterns.ts +77 -77
- package/src/core/CacheManager.ts +169 -159
- package/src/core/ConditionalBuilder.ts +382 -382
- package/src/core/ConditionalRuntime.ts +27 -27
- package/src/core/ConditionalValidator.ts +254 -254
- package/src/core/DslBuilder.ts +687 -677
- package/src/core/ErrorCodes.ts +38 -38
- package/src/core/ErrorFormatter.ts +271 -271
- package/src/core/JSONSchemaCore.ts +65 -65
- package/src/core/Locale.ts +187 -187
- package/src/core/MessageTemplate.ts +42 -42
- package/src/core/ObjectDslBuilder.ts +64 -64
- package/src/core/PluginManager.ts +326 -326
- package/src/core/StringExtensions.ts +140 -140
- package/src/core/TemplateEngine.ts +44 -44
- package/src/core/Validator.ts +448 -448
- package/src/errors/I18nError.ts +159 -159
- package/src/errors/ValidationError.ts +105 -105
- package/src/exporters/BaseExporter.ts +60 -60
- package/src/exporters/MarkdownExporter.ts +305 -305
- package/src/exporters/MongoDBExporter.ts +126 -126
- package/src/exporters/MySQLExporter.ts +156 -155
- package/src/exporters/PostgreSQLExporter.ts +222 -222
- package/src/exporters/index.ts +18 -18
- package/src/index.ts +651 -633
- package/src/locales/en-US.ts +160 -160
- package/src/locales/es-ES.ts +160 -160
- package/src/locales/fr-FR.ts +160 -160
- package/src/locales/index.ts +103 -103
- package/src/locales/ja-JP.ts +160 -160
- package/src/locales/types.ts +156 -156
- package/src/locales/zh-CN.ts +160 -160
- package/src/parser/ConstraintParser.ts +101 -101
- package/src/parser/DslParser.ts +470 -470
- package/src/parser/SchemaCompiler.ts +66 -66
- package/src/parser/TypeRegistry.ts +250 -250
- package/src/parser/index.ts +6 -6
- package/src/plugins/custom-format.ts +124 -126
- package/src/plugins/custom-type-example.ts +106 -108
- package/src/plugins/custom-validator.ts +138 -140
- package/src/types/conditional.ts +28 -28
- package/src/types/config.ts +59 -59
- package/src/types/dsl.ts +131 -131
- package/src/types/error.ts +60 -60
- package/src/types/index.ts +17 -17
- package/src/types/infer.ts +127 -127
- package/src/types/plugin.ts +58 -58
- package/src/types/safe-regex.d.ts +9 -9
- package/src/types/schema.ts +66 -66
- package/src/types/validate.ts +71 -71
- package/src/utils/SchemaHelper.ts +196 -196
- package/src/utils/SchemaUtils.ts +365 -346
- package/src/utils/TypeConverter.ts +215 -215
- package/src/utils/index.ts +10 -10
- package/src/validators/CustomKeywords.ts +477 -477
package/docs/api-reference.md
CHANGED
|
@@ -1,1047 +1,1047 @@
|
|
|
1
|
-
# schema-dsl API 参考文档
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
> **更新时间**: 2026-05-22
|
|
5
|
-
|
|
6
|
-
---
|
|
7
|
-
|
|
8
|
-
## 📑 目录
|
|
9
|
-
|
|
10
|
-
- [dsl() 函数](#dsl-函数)
|
|
11
|
-
- [DslBuilder 类](#dslbuilder-类)
|
|
12
|
-
- [String 扩展](#string-扩展)
|
|
13
|
-
- [Validator 类](#validator-类)
|
|
14
|
-
- [导出器](#导出器)
|
|
15
|
-
- [工具函数](#工具函数)
|
|
16
|
-
|
|
17
|
-
---
|
|
18
|
-
|
|
19
|
-
## dsl() 函数
|
|
20
|
-
|
|
21
|
-
### 描述
|
|
22
|
-
|
|
23
|
-
DSL 主入口函数,支持字符串和对象两种定义方式。
|
|
24
|
-
|
|
25
|
-
### 语法
|
|
26
|
-
|
|
27
|
-
```javascript
|
|
28
|
-
dsl(definition: string | object): DslBuilder | JSONSchema
|
|
29
|
-
```
|
|
30
|
-
|
|
31
|
-
### 参数
|
|
32
|
-
|
|
33
|
-
- `definition` (**string** | **object**) - DSL定义
|
|
34
|
-
- 字符串:返回 DslBuilder 实例(可链式调用)
|
|
35
|
-
- 对象:返回 JSON Schema 对象
|
|
36
|
-
|
|
37
|
-
### 返回值
|
|
38
|
-
|
|
39
|
-
- **DslBuilder** - 当参数为字符串时
|
|
40
|
-
- **Object** - 当参数为对象时(JSON Schema)
|
|
41
|
-
|
|
42
|
-
### 示例
|
|
43
|
-
|
|
44
|
-
```javascript
|
|
45
|
-
// 字符串:返回 DslBuilder
|
|
46
|
-
const builder = dsl('email!');
|
|
47
|
-
builder.pattern(/custom/).label('邮箱');
|
|
48
|
-
|
|
49
|
-
// 对象:返回 JSON Schema
|
|
50
|
-
const schema = dsl({
|
|
51
|
-
username: 'string:3-32!',
|
|
52
|
-
email: 'email!'
|
|
53
|
-
});
|
|
54
|
-
```
|
|
55
|
-
|
|
56
|
-
---
|
|
57
|
-
|
|
58
|
-
## DslBuilder 类
|
|
59
|
-
|
|
60
|
-
### 描述
|
|
61
|
-
|
|
62
|
-
Schema 构建器类,支持链式调用添加验证规则。
|
|
63
|
-
|
|
64
|
-
### 构造函数
|
|
65
|
-
|
|
66
|
-
```javascript
|
|
67
|
-
new DslBuilder(dslString: string)
|
|
68
|
-
```
|
|
69
|
-
|
|
70
|
-
**参数**:
|
|
71
|
-
- `dslString` (**string**) - DSL字符串,如 `'string:3-32!'`
|
|
72
|
-
|
|
73
|
-
### 方法
|
|
74
|
-
|
|
75
|
-
#### `.pattern(regex, message?)`
|
|
76
|
-
|
|
77
|
-
添加正则表达式验证。
|
|
78
|
-
|
|
79
|
-
**参数**:
|
|
80
|
-
- `regex` (**RegExp** | **string**) - 正则表达式
|
|
81
|
-
- `message` (**string**, 可选) - 自定义错误消息
|
|
82
|
-
|
|
83
|
-
**返回**: **DslBuilder**
|
|
84
|
-
|
|
85
|
-
**示例**:
|
|
86
|
-
```javascript
|
|
87
|
-
dsl('string:3-32!')
|
|
88
|
-
.pattern(/^[a-zA-Z0-9_]+$/, '只能包含字母、数字和下划线')
|
|
89
|
-
```
|
|
90
|
-
|
|
91
|
-
---
|
|
92
|
-
|
|
93
|
-
#### `.label(text)`
|
|
94
|
-
|
|
95
|
-
设置字段标签(用于错误消息)。
|
|
96
|
-
|
|
97
|
-
**参数**:
|
|
98
|
-
- `text` (**string**) - 标签文本
|
|
99
|
-
|
|
100
|
-
**返回**: **DslBuilder**
|
|
101
|
-
|
|
102
|
-
**示例**:
|
|
103
|
-
```javascript
|
|
104
|
-
dsl('email!').label('邮箱地址')
|
|
105
|
-
```
|
|
106
|
-
|
|
107
|
-
---
|
|
108
|
-
|
|
109
|
-
#### `.messages(messages)`
|
|
110
|
-
|
|
111
|
-
自定义错误消息。
|
|
112
|
-
|
|
113
|
-
**参数**:
|
|
114
|
-
- `messages` (**Object**) - 错误消息对象
|
|
115
|
-
- 键:错误代码(如 `'string.min'`)
|
|
116
|
-
- 值:错误消息模板
|
|
117
|
-
|
|
118
|
-
**返回**: **DslBuilder**
|
|
119
|
-
|
|
120
|
-
**示例**:
|
|
121
|
-
```javascript
|
|
122
|
-
dsl('string:3-32!')
|
|
123
|
-
.messages({
|
|
124
|
-
'min': '至少{{#limit}}个字符',
|
|
125
|
-
'max': '最多{{#limit}}个字符'
|
|
126
|
-
})
|
|
127
|
-
```
|
|
128
|
-
|
|
129
|
-
---
|
|
130
|
-
|
|
131
|
-
#### `.description(text)`
|
|
132
|
-
|
|
133
|
-
设置字段描述。
|
|
134
|
-
|
|
135
|
-
**参数**:
|
|
136
|
-
- `text` (**string**) - 描述文本
|
|
137
|
-
|
|
138
|
-
**返回**: **DslBuilder**
|
|
139
|
-
|
|
140
|
-
**示例**:
|
|
141
|
-
```javascript
|
|
142
|
-
dsl('url').description('个人主页链接')
|
|
143
|
-
```
|
|
144
|
-
|
|
145
|
-
---
|
|
146
|
-
|
|
147
|
-
#### `.custom(validator)`
|
|
148
|
-
|
|
149
|
-
添加自定义验证器。
|
|
150
|
-
|
|
151
|
-
**参数**:
|
|
152
|
-
- `validator` (**Function**) - 验证函数
|
|
153
|
-
- 签名:`(value) => boolean | string | { error, message } | void`
|
|
154
|
-
- 返回 `true` 表示通过
|
|
155
|
-
- 返回 `false`、错误消息字符串或错误对象表示失败
|
|
156
|
-
- 同步验证器由 `validate()` 和 `validateAsync()` 均执行;异步验证器(返回 `Promise`)仅由 `validateAsync()` 执行,`validate()` 调用时会跳过异步 validator
|
|
157
|
-
|
|
158
|
-
**返回**: **DslBuilder**
|
|
159
|
-
|
|
160
|
-
**示例**:
|
|
161
|
-
```javascript
|
|
162
|
-
dsl('string:3-32!')
|
|
163
|
-
.custom((value) => {
|
|
164
|
-
if (value === 'admin') {
|
|
165
|
-
return { error: 'username.exists', message: '用户名已存在' };
|
|
166
|
-
}
|
|
167
|
-
})
|
|
168
|
-
```
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
---
|
|
172
|
-
|
|
173
|
-
#### `.default(value)`
|
|
174
|
-
|
|
175
|
-
设置默认值。
|
|
176
|
-
|
|
177
|
-
**参数**:
|
|
178
|
-
- `value` (**any**) - 默认值
|
|
179
|
-
|
|
180
|
-
**返回**: **DslBuilder**
|
|
181
|
-
|
|
182
|
-
**示例**:
|
|
183
|
-
```javascript
|
|
184
|
-
dsl('string').default('guest')
|
|
185
|
-
```
|
|
186
|
-
|
|
187
|
-
---
|
|
188
|
-
|
|
189
|
-
#### `.username(preset?)`
|
|
190
|
-
|
|
191
|
-
用户名验证(自动设置长度和正则)。
|
|
192
|
-
|
|
193
|
-
**参数**:
|
|
194
|
-
- `preset` (**string** | **Object**, 可选) - 预设配置
|
|
195
|
-
- 字符串:`'short'` | `'medium'` | `'long'` | `'5-20'`
|
|
196
|
-
- 对象:`{ minLength, maxLength, allowUnderscore, allowNumber }`
|
|
197
|
-
- 默认值:`'medium'` (3-32位)
|
|
198
|
-
|
|
199
|
-
**返回**: **DslBuilder**
|
|
200
|
-
|
|
201
|
-
**示例**:
|
|
202
|
-
```javascript
|
|
203
|
-
// 默认 medium (3-32位)
|
|
204
|
-
dsl('string!').username()
|
|
205
|
-
|
|
206
|
-
// 自定义范围
|
|
207
|
-
dsl('string!').username('5-20')
|
|
208
|
-
|
|
209
|
-
// 使用预设
|
|
210
|
-
dsl('string!').username('short') // 3-16位
|
|
211
|
-
```
|
|
212
|
-
|
|
213
|
-
---
|
|
214
|
-
|
|
215
|
-
#### `.password(strength?)`
|
|
216
|
-
|
|
217
|
-
密码强度验证(自动设置长度和正则)。
|
|
218
|
-
|
|
219
|
-
**参数**:
|
|
220
|
-
- `strength` (**string**, 可选) - 强度级别
|
|
221
|
-
- `'weak'` - 最少6位
|
|
222
|
-
- `'medium'` - 8位,字母+数字(默认)
|
|
223
|
-
- `'strong'` - 8位,大小写+数字
|
|
224
|
-
- `'veryStrong'` - 10位,大小写+数字+特殊字符
|
|
225
|
-
|
|
226
|
-
**返回**: **DslBuilder**
|
|
227
|
-
|
|
228
|
-
**示例**:
|
|
229
|
-
```javascript
|
|
230
|
-
dsl('string!').password('strong')
|
|
231
|
-
```
|
|
232
|
-
|
|
233
|
-
---
|
|
234
|
-
|
|
235
|
-
#### `.phone(country?)`
|
|
236
|
-
|
|
237
|
-
手机号验证(自动设置长度和正则)。
|
|
238
|
-
|
|
239
|
-
**参数**:
|
|
240
|
-
- `country` (**string**, 可选) - 国家代码
|
|
241
|
-
- `'cn'` - 中国(默认)
|
|
242
|
-
- `'us'` - 美国
|
|
243
|
-
- `'uk'` - 英国
|
|
244
|
-
- `'hk'` - 香港
|
|
245
|
-
- `'tw'` - 台湾
|
|
246
|
-
- `'international'` - 国际格式
|
|
247
|
-
|
|
248
|
-
**返回**: **DslBuilder**
|
|
249
|
-
|
|
250
|
-
**注意**: 自动将类型纠正为 `string`(即使写成 `number` 也会自动修正)
|
|
251
|
-
|
|
252
|
-
**示例**:
|
|
253
|
-
```javascript
|
|
254
|
-
// 推荐写法
|
|
255
|
-
dsl('string!').phone('cn')
|
|
256
|
-
|
|
257
|
-
// 自动纠正:number → string
|
|
258
|
-
dsl('number!').phone('cn') // 自动纠正为 string
|
|
259
|
-
```
|
|
260
|
-
|
|
261
|
-
---
|
|
262
|
-
|
|
263
|
-
#### `.toSchema()`
|
|
264
|
-
|
|
265
|
-
转换为 JSON Schema 对象(含内部标记)。
|
|
266
|
-
|
|
267
|
-
**返回**: **Object** - JSON Schema 对象(包含 `_required`、`_customMessages`、`_label` 等 schema-dsl 内部字段)
|
|
268
|
-
|
|
269
|
-
**示例**:
|
|
270
|
-
```javascript
|
|
271
|
-
const schema = dsl('email!').label('邮箱').toSchema();
|
|
272
|
-
// { type: 'string', format: 'email', _label: '邮箱', _required: true }
|
|
273
|
-
```
|
|
274
|
-
|
|
275
|
-
---
|
|
276
|
-
|
|
277
|
-
#### `.toJsonSchema()` <sup>v1.2.5+</sup>
|
|
278
|
-
|
|
279
|
-
转换为纯净的 JSON Schema 对象(无内部标记)。
|
|
280
|
-
|
|
281
|
-
与 `toSchema()` 不同,`toJsonSchema()` 会自动清理所有 schema-dsl 内部标记:
|
|
282
|
-
- **下划线前缀字段**:`_required`、`_customMessages`、`_label`、`_customValidators`、`_whenConditions`
|
|
283
|
-
- **自定义验证关键字(直接清除)**:`alphanum`、`lowercase`、`uppercase`、`trim`、`jsonString`、`port`、`requiredAll`、`strictSchema`、`noSparse`、`includesRequired`、`dateFormat`、`dateGreater`、`dateLess`、`precision`
|
|
284
|
-
- **`exactLength` 特殊翻译**:不直接清除,而是转换为标准 JSON Schema `{ minLength: N, maxLength: N }`(与 v1 DslBuilder `string:N` 行为兼容)
|
|
285
|
-
|
|
286
|
-
> ⚠️ `multipleOf` 是标准 JSON Schema 字段,**不会**被清除(v2 修复了 v1 的错误行为)。
|
|
287
|
-
|
|
288
|
-
返回的对象可直接嵌入 OpenAPI / JSON Schema 等标准文档中,无需下游再做清理。
|
|
289
|
-
|
|
290
|
-
**返回**: **Object** - 纯净的 JSON Schema 对象
|
|
291
|
-
|
|
292
|
-
**适用场景**:
|
|
293
|
-
- 生成 OpenAPI 文档
|
|
294
|
-
- 导出给外部系统消费
|
|
295
|
-
- 任何需要标准 JSON Schema 的场景
|
|
296
|
-
|
|
297
|
-
**示例**:
|
|
298
|
-
```javascript
|
|
299
|
-
// 对比 toSchema() 与 toJsonSchema()
|
|
300
|
-
const builder = dsl('string:3-32!').label('用户名').messages({ min: '至少3个字符' });
|
|
301
|
-
|
|
302
|
-
builder.toSchema();
|
|
303
|
-
// { type: 'string', minLength: 3, maxLength: 32, _required: true, _label: '用户名', _customMessages: { min: '至少3个字符' } }
|
|
304
|
-
|
|
305
|
-
builder.toJsonSchema();
|
|
306
|
-
// { type: 'string', minLength: 3, maxLength: 32 }
|
|
307
|
-
// 注意:不含 _required、_label、_customMessages 等内部字段
|
|
308
|
-
|
|
309
|
-
// string:N 单值语法(exactLength → minLength + maxLength)
|
|
310
|
-
const exact = dsl('string:6!');
|
|
311
|
-
exact.toSchema();
|
|
312
|
-
// { type: 'string', exactLength: 6, _required: true }
|
|
313
|
-
exact.toJsonSchema();
|
|
314
|
-
// { type: 'string', minLength: 6, maxLength: 6 }
|
|
315
|
-
// 注:exactLength 自动翻译为标准 JSON Schema 的 minLength + maxLength(v1 兼容行为)
|
|
316
|
-
|
|
317
|
-
// enum 示例
|
|
318
|
-
const enumBuilder = dsl('enum:admin,user,guest!');
|
|
319
|
-
enumBuilder.toJsonSchema();
|
|
320
|
-
// { type: 'string', enum: ['admin', 'user', 'guest'] }
|
|
321
|
-
|
|
322
|
-
// 用于 OpenAPI 文档生成
|
|
323
|
-
const schema = dsl({
|
|
324
|
-
username: 'string:3-32!',
|
|
325
|
-
email: 'email!',
|
|
326
|
-
age: 'number:0-120'
|
|
327
|
-
});
|
|
328
|
-
// 遍历各字段调用 toJsonSchema() 即可获得标准 JSON Schema
|
|
329
|
-
```
|
|
330
|
-
|
|
331
|
-
---
|
|
332
|
-
|
|
333
|
-
#### `.validate(data)`
|
|
334
|
-
|
|
335
|
-
验证数据(便捷方法)。
|
|
336
|
-
|
|
337
|
-
**参数**:
|
|
338
|
-
- `data` (**any**) - 待验证数据
|
|
339
|
-
|
|
340
|
-
**返回**: **Promise<Object>** - 验证结果
|
|
341
|
-
- `valid` (**boolean**) - 是否通过
|
|
342
|
-
- `errors` (**Array**, 可选) - 错误列表
|
|
343
|
-
- `data` (**any**, 可选) - 验证通过的数据
|
|
344
|
-
|
|
345
|
-
**示例**:
|
|
346
|
-
```javascript
|
|
347
|
-
const result = await dsl('email!').validate('user@example.com');
|
|
348
|
-
console.log(result.valid); // true
|
|
349
|
-
```
|
|
350
|
-
|
|
351
|
-
---
|
|
352
|
-
|
|
353
|
-
### 静态方法
|
|
354
|
-
|
|
355
|
-
#### `dsl.match(field, map)```
|
|
356
|
-
|
|
357
|
-
创建条件验证规则(类似 switch-case)。
|
|
358
|
-
|
|
359
|
-
**参数**:
|
|
360
|
-
- `field` (**string**) - 依赖的字段名
|
|
361
|
-
- `map` (**Object**) - 值与Schema的映射
|
|
362
|
-
- `[value: string]`: 对应的Schema
|
|
363
|
-
- `_default` (**optional**): 默认Schema
|
|
364
|
-
|
|
365
|
-
**返回**: **Object** - 内部Match结构
|
|
366
|
-
|
|
367
|
-
**示例**:
|
|
368
|
-
```javascript
|
|
369
|
-
dsl.match('type', {
|
|
370
|
-
email: 'email!',
|
|
371
|
-
phone: 'string:11!',
|
|
372
|
-
_default: 'string'
|
|
373
|
-
})
|
|
374
|
-
```
|
|
375
|
-
|
|
376
|
-
#### `dsl.if(condition, thenSchema, elseSchema)`
|
|
377
|
-
|
|
378
|
-
创建简单的条件验证规则。
|
|
379
|
-
|
|
380
|
-
**参数**:
|
|
381
|
-
- `condition` (**string**) - 条件字段名
|
|
382
|
-
- `thenSchema` (**string|Object**) - 满足条件时的Schema
|
|
383
|
-
- `elseSchema` (**string|Object**, 可选) - 不满足条件时的Schema
|
|
384
|
-
|
|
385
|
-
**返回**: **Object** - 内部If结构
|
|
386
|
-
|
|
387
|
-
**示例**:
|
|
388
|
-
```javascript
|
|
389
|
-
dsl.if('isVip', 'number:0-50', 'number:0-10')
|
|
390
|
-
```
|
|
391
|
-
|
|
392
|
-
---
|
|
393
|
-
|
|
394
|
-
## 运行时辅助函数
|
|
395
|
-
|
|
396
|
-
### `dsl.config(options)`
|
|
397
|
-
|
|
398
|
-
全局配置入口,在应用启动时调用一次,设置 i18n、缓存、自定义正则和严格类型解析模式。
|
|
399
|
-
|
|
400
|
-
```javascript
|
|
401
|
-
const { dsl } = require('schema-dsl');
|
|
402
|
-
|
|
403
|
-
dsl.config({
|
|
404
|
-
// i18n:内置语言包路径 / 内联 locale bundle / { localesPath } / { locales }
|
|
405
|
-
i18n: './locales',
|
|
406
|
-
|
|
407
|
-
// 默认语言(默认 'en-US')
|
|
408
|
-
defaultLocale: 'zh-CN',
|
|
409
|
-
|
|
410
|
-
// 编译缓存配置
|
|
411
|
-
cache: { maxSize: 2000, ttl: 0, enabled: true },
|
|
412
|
-
|
|
413
|
-
// strict: true → 遇到未知类型直接抛出 Error(默认 false:warn + 回退 string)
|
|
414
|
-
strict: true,
|
|
415
|
-
|
|
416
|
-
// 追加自定义正则规则(phone / idCard / creditCard 等)
|
|
417
|
-
patterns: {
|
|
418
|
-
phone: { us: /^\+1\d{10}$/ }
|
|
419
|
-
}
|
|
420
|
-
});
|
|
421
|
-
```
|
|
422
|
-
|
|
423
|
-
**参数** (`DslConfigOptions`):
|
|
424
|
-
|
|
425
|
-
| 字段 | 类型 | 默认 | 说明 |
|
|
426
|
-
|------|------|------|------|
|
|
427
|
-
| `i18n` | `string \| object` | — | 语言包路径或内联对象 |
|
|
428
|
-
| `defaultLocale` | `string` | `'en-US'` | 默认语言 |
|
|
429
|
-
| `cache` | `CacheOptions` | — | `maxSize` / `ttl` / `enabled` / `statsEnabled` |
|
|
430
|
-
| `strict` | `boolean` | `false` | `true` 时解析未知 DSL 类型抛出 Error |
|
|
431
|
-
| `patterns` | `object` | — | 追加自定义格式正则(phone/idCard/creditCard) |
|
|
432
|
-
|
|
433
|
-
---
|
|
434
|
-
|
|
435
|
-
### `getDefaultValidator()`
|
|
436
|
-
|
|
437
|
-
获取顶层 `validate()` / `validateAsync()` 便捷函数内部复用的默认 `Validator` 单例。
|
|
438
|
-
|
|
439
|
-
```javascript
|
|
440
|
-
const { getDefaultValidator } = require('schema-dsl');
|
|
441
|
-
|
|
442
|
-
const validator = getDefaultValidator();
|
|
443
|
-
console.log(validator.getCacheStats());
|
|
444
|
-
```
|
|
445
|
-
|
|
446
|
-
---
|
|
447
|
-
|
|
448
|
-
### `resetDefaultValidator()`
|
|
449
|
-
|
|
450
|
-
重置顶层 `validate()` / `validateAsync()` 使用的默认 `Validator` 单例。
|
|
451
|
-
|
|
452
|
-
```javascript
|
|
453
|
-
const { resetDefaultValidator } = require('schema-dsl');
|
|
454
|
-
|
|
455
|
-
resetDefaultValidator();
|
|
456
|
-
```
|
|
457
|
-
|
|
458
|
-
---
|
|
459
|
-
|
|
460
|
-
### `installStringExtensions(dslFunction?)`
|
|
461
|
-
|
|
462
|
-
手动安装 String 扩展。模块导入时默认已自动安装;只有在调用过 `uninstallStringExtensions()` 或需要显式恢复扩展时才需要手动执行。
|
|
463
|
-
|
|
464
|
-
```javascript
|
|
465
|
-
const { installStringExtensions } = require('schema-dsl');
|
|
466
|
-
|
|
467
|
-
installStringExtensions();
|
|
468
|
-
```
|
|
469
|
-
|
|
470
|
-
---
|
|
471
|
-
|
|
472
|
-
### `uninstallStringExtensions()`
|
|
473
|
-
|
|
474
|
-
卸载挂载到 `String.prototype` 上的扩展方法。
|
|
475
|
-
|
|
476
|
-
```javascript
|
|
477
|
-
const { uninstallStringExtensions } = require('schema-dsl');
|
|
478
|
-
|
|
479
|
-
uninstallStringExtensions();
|
|
480
|
-
```
|
|
481
|
-
|
|
482
|
-
---
|
|
483
|
-
|
|
484
|
-
## Validator 类
|
|
485
|
-
|
|
486
|
-
**参数**:
|
|
487
|
-
- `options` (**Object**, 可选) - Validator 配置项
|
|
488
|
-
|
|
489
|
-
### 方法
|
|
490
|
-
|
|
491
|
-
#### `.compile(schema, cacheKey?)`
|
|
492
|
-
|
|
493
|
-
编译 Schema 为 AJV 验证函数。
|
|
494
|
-
|
|
495
|
-
**参数**:
|
|
496
|
-
- `schema` (**Object**) - JSON Schema
|
|
497
|
-
- `cacheKey` (**string** | **null**, 可选) - 缓存键
|
|
498
|
-
|
|
499
|
-
**返回**: **Function** - AJV 验证函数
|
|
500
|
-
|
|
501
|
-
**示例**:
|
|
502
|
-
```javascript
|
|
503
|
-
const validator = new Validator();
|
|
504
|
-
const validate = validator.compile(schema, 'user-schema');
|
|
505
|
-
const ok = validate(data);
|
|
506
|
-
```
|
|
507
|
-
|
|
508
|
-
---
|
|
509
|
-
|
|
510
|
-
#### `.validate(schema, data, options?)`
|
|
511
|
-
|
|
512
|
-
同步验证。
|
|
513
|
-
|
|
514
|
-
**参数**:
|
|
515
|
-
- `schema` (**Object** | **Function**) - JSON Schema 或已编译的验证函数
|
|
516
|
-
- `data` (**any**) - 待验证数据
|
|
517
|
-
- `options` (**Object**, 可选) - 验证选项
|
|
518
|
-
|
|
519
|
-
**返回**: **Object**
|
|
520
|
-
- `valid` (**boolean**) - 是否通过
|
|
521
|
-
- `errors` (**Array**, 可选) - 错误列表
|
|
522
|
-
- `data` (**any**, 可选) - 经过处理后的数据
|
|
523
|
-
|
|
524
|
-
**示例**:
|
|
525
|
-
```javascript
|
|
526
|
-
const validator = new Validator();
|
|
527
|
-
const result = validator.validate(schema, payload);
|
|
528
|
-
console.log(result.valid);
|
|
529
|
-
```
|
|
530
|
-
|
|
531
|
-
---
|
|
532
|
-
|
|
533
|
-
#### `.validateAsync(schema, data, options?)`
|
|
534
|
-
|
|
535
|
-
异步验证。验证失败时抛出 `ValidationError`。
|
|
536
|
-
|
|
537
|
-
**参数**:
|
|
538
|
-
- `schema` (**Object** | **Function**) - JSON Schema 或已编译的验证函数
|
|
539
|
-
- `data` (**any**) - 待验证数据
|
|
540
|
-
- `options` (**Object**, 可选) - 验证选项
|
|
541
|
-
|
|
542
|
-
**返回**: **Promise<any>** - 验证通过后的数据
|
|
543
|
-
|
|
544
|
-
**示例**:
|
|
545
|
-
```javascript
|
|
546
|
-
const validator = new Validator();
|
|
547
|
-
await validator.validateAsync(schema, payload);
|
|
548
|
-
```
|
|
549
|
-
|
|
550
|
-
---
|
|
551
|
-
|
|
552
|
-
#### `.validateBatch(schema, dataArray)`
|
|
553
|
-
|
|
554
|
-
批量验证。Schema 只编译一次,多次复用。
|
|
555
|
-
|
|
556
|
-
**参数**:
|
|
557
|
-
- `schema` (**Object**) - JSON Schema
|
|
558
|
-
- `dataArray` (**Array**) - 待验证数据数组
|
|
559
|
-
|
|
560
|
-
**返回**: **Array<Object>** - 每项对应一个验证结果
|
|
561
|
-
|
|
562
|
-
**示例**:
|
|
563
|
-
```javascript
|
|
564
|
-
const validator = new Validator();
|
|
565
|
-
const results = validator.validateBatch(schema, records);
|
|
566
|
-
```
|
|
567
|
-
|
|
568
|
-
---
|
|
569
|
-
|
|
570
|
-
#### `.addKeyword(keyword, definition)`
|
|
571
|
-
|
|
572
|
-
添加 AJV 自定义关键字。
|
|
573
|
-
|
|
574
|
-
**参数**:
|
|
575
|
-
- `keyword` (**string**) - 关键字名称
|
|
576
|
-
- `definition` (**Object**) - AJV 关键字定义
|
|
577
|
-
|
|
578
|
-
**返回**: **Validator**
|
|
579
|
-
|
|
580
|
-
**示例**:
|
|
581
|
-
```javascript
|
|
582
|
-
const validator = new Validator();
|
|
583
|
-
validator.addKeyword('isEven', {
|
|
584
|
-
type: 'number',
|
|
585
|
-
validate: (_schema, data) => data % 2 === 0
|
|
586
|
-
});
|
|
587
|
-
```
|
|
588
|
-
|
|
589
|
-
---
|
|
590
|
-
|
|
591
|
-
#### `.addFormat(name, validator)`
|
|
592
|
-
|
|
593
|
-
添加 AJV 自定义格式。
|
|
594
|
-
|
|
595
|
-
**参数**:
|
|
596
|
-
- `name` (**string**) - 格式名称
|
|
597
|
-
- `validator` (**Function** | **Object**) - AJV format 定义
|
|
598
|
-
|
|
599
|
-
**返回**: **Validator**
|
|
600
|
-
|
|
601
|
-
**示例**:
|
|
602
|
-
```javascript
|
|
603
|
-
const validator = new Validator();
|
|
604
|
-
validator.addFormat('phone-cn', /^1[3-9]\d{9}$/);
|
|
605
|
-
```
|
|
606
|
-
|
|
607
|
-
---
|
|
608
|
-
|
|
609
|
-
#### `.addSchema(uri, schema)`
|
|
610
|
-
|
|
611
|
-
添加 schema 引用。
|
|
612
|
-
|
|
613
|
-
**参数**:
|
|
614
|
-
- `uri` (**string**) - schema 标识
|
|
615
|
-
- `schema` (**Object**) - JSON Schema
|
|
616
|
-
|
|
617
|
-
**返回**: **Validator**
|
|
618
|
-
|
|
619
|
-
**示例**:
|
|
620
|
-
```javascript
|
|
621
|
-
const validator = new Validator();
|
|
622
|
-
validator.addSchema('user.schema.json', schema);
|
|
623
|
-
```
|
|
624
|
-
|
|
625
|
-
---
|
|
626
|
-
|
|
627
|
-
#### `.removeSchema(uri)`
|
|
628
|
-
|
|
629
|
-
删除 schema 引用。
|
|
630
|
-
|
|
631
|
-
**参数**:
|
|
632
|
-
- `uri` (**string**) - schema 标识
|
|
633
|
-
|
|
634
|
-
**返回**: **Validator**
|
|
635
|
-
|
|
636
|
-
**示例**:
|
|
637
|
-
```javascript
|
|
638
|
-
const validator = new Validator();
|
|
639
|
-
validator.removeSchema('user.schema.json');
|
|
640
|
-
```
|
|
641
|
-
|
|
642
|
-
---
|
|
643
|
-
|
|
644
|
-
#### `.getAjv()`
|
|
645
|
-
|
|
646
|
-
获取底层 AJV 实例。
|
|
647
|
-
|
|
648
|
-
**返回**: **Ajv**
|
|
649
|
-
|
|
650
|
-
**示例**:
|
|
651
|
-
```javascript
|
|
652
|
-
const validator = new Validator();
|
|
653
|
-
const ajv = validator.getAjv();
|
|
654
|
-
```
|
|
655
|
-
|
|
656
|
-
---
|
|
657
|
-
|
|
658
|
-
#### `.clearCache()`
|
|
659
|
-
|
|
660
|
-
清空编译缓存。
|
|
661
|
-
|
|
662
|
-
**返回**: `void`
|
|
663
|
-
|
|
664
|
-
**示例**:
|
|
665
|
-
```javascript
|
|
666
|
-
const validator = new Validator();
|
|
667
|
-
validator.clearCache();
|
|
668
|
-
```
|
|
669
|
-
|
|
670
|
-
---
|
|
671
|
-
|
|
672
|
-
#### `.getCacheStats()`
|
|
673
|
-
|
|
674
|
-
获取缓存统计信息。
|
|
675
|
-
|
|
676
|
-
**返回**: **Object**
|
|
677
|
-
|
|
678
|
-
**示例**:
|
|
679
|
-
```javascript
|
|
680
|
-
const validator = new Validator();
|
|
681
|
-
console.log(validator.getCacheStats());
|
|
682
|
-
```
|
|
683
|
-
|
|
684
|
-
---
|
|
685
|
-
|
|
686
|
-
### 静态方法
|
|
687
|
-
|
|
688
|
-
#### `Validator.create(options?)`
|
|
689
|
-
|
|
690
|
-
创建 `Validator` 实例。
|
|
691
|
-
|
|
692
|
-
**返回**: **Validator**
|
|
693
|
-
|
|
694
|
-
**示例**:
|
|
695
|
-
```javascript
|
|
696
|
-
const validator = Validator.create();
|
|
697
|
-
```
|
|
698
|
-
|
|
699
|
-
---
|
|
700
|
-
|
|
701
|
-
#### `Validator.quickValidate(schema, data)`
|
|
702
|
-
|
|
703
|
-
快速验证。
|
|
704
|
-
|
|
705
|
-
**参数**:
|
|
706
|
-
- `schema` (**Object**) - JSON Schema
|
|
707
|
-
- `data` (**any**) - 待验证数据
|
|
708
|
-
|
|
709
|
-
**返回**: **boolean**
|
|
710
|
-
|
|
711
|
-
**示例**:
|
|
712
|
-
```javascript
|
|
713
|
-
const ok = Validator.quickValidate(schema, data);
|
|
714
|
-
```
|
|
715
|
-
|
|
716
|
-
---
|
|
717
|
-
|
|
718
|
-
## 导出器
|
|
719
|
-
|
|
720
|
-
### MongoDBExporter
|
|
721
|
-
|
|
722
|
-
导出为 MongoDB 验证Schema。
|
|
723
|
-
|
|
724
|
-
```javascript
|
|
725
|
-
const { MongoDBExporter } = require('schema-dsl');
|
|
726
|
-
|
|
727
|
-
const exporter = new MongoDBExporter({ strict: true });
|
|
728
|
-
const mongoSchema = exporter.export(jsonSchema);
|
|
729
|
-
const command = exporter.generateCommand('users', jsonSchema);
|
|
730
|
-
```
|
|
731
|
-
|
|
732
|
-
**方法**:
|
|
733
|
-
- `export(schema)` - 导出为MongoDB Schema
|
|
734
|
-
- `generateCommand(collection, schema)` - 生成 createCollection 命令
|
|
735
|
-
|
|
736
|
-
---
|
|
737
|
-
|
|
738
|
-
### MySQLExporter
|
|
739
|
-
|
|
740
|
-
导出为 MySQL DDL。
|
|
741
|
-
|
|
742
|
-
```javascript
|
|
743
|
-
const { MySQLExporter } = require('schema-dsl');
|
|
744
|
-
|
|
745
|
-
const exporter = new MySQLExporter();
|
|
746
|
-
const ddl = exporter.export('users', jsonSchema);
|
|
747
|
-
```
|
|
748
|
-
|
|
749
|
-
**方法**:
|
|
750
|
-
- `export(tableName, schema)` - 导出为MySQL DDL
|
|
751
|
-
|
|
752
|
-
---
|
|
753
|
-
|
|
754
|
-
### PostgreSQLExporter
|
|
755
|
-
|
|
756
|
-
导出为 PostgreSQL DDL。
|
|
757
|
-
|
|
758
|
-
```javascript
|
|
759
|
-
const { PostgreSQLExporter } = require('schema-dsl');
|
|
760
|
-
|
|
761
|
-
const exporter = new PostgreSQLExporter();
|
|
762
|
-
const ddl = exporter.export('users', jsonSchema);
|
|
763
|
-
```
|
|
764
|
-
|
|
765
|
-
**方法**:
|
|
766
|
-
- `export(tableName, schema)` - 导出为PostgreSQL DDL
|
|
767
|
-
|
|
768
|
-
---
|
|
769
|
-
|
|
770
|
-
## 工具函数
|
|
771
|
-
|
|
772
|
-
### TypeConverter
|
|
773
|
-
|
|
774
|
-
类型转换工具。
|
|
775
|
-
|
|
776
|
-
```javascript
|
|
777
|
-
const { TypeConverter } = require('schema-dsl');
|
|
778
|
-
|
|
779
|
-
TypeConverter.toJSONSchemaType('string');
|
|
780
|
-
TypeConverter.toMongoDBType('integer');
|
|
781
|
-
```
|
|
782
|
-
|
|
783
|
-
---
|
|
784
|
-
|
|
785
|
-
### SchemaHelper
|
|
786
|
-
|
|
787
|
-
Schema辅助工具。
|
|
788
|
-
|
|
789
|
-
```javascript
|
|
790
|
-
const { SchemaHelper } = require('schema-dsl');
|
|
791
|
-
|
|
792
|
-
SchemaHelper.merge(schema1, schema2);
|
|
793
|
-
SchemaHelper.clone(schema);
|
|
794
|
-
```
|
|
795
|
-
|
|
796
|
-
---
|
|
797
|
-
|
|
798
|
-
### ErrorFormatter
|
|
799
|
-
|
|
800
|
-
验证错误格式化工具,用于把 Ajv 原始错误数组或简化错误对象转换成统一的错误项结构或消息文本。
|
|
801
|
-
|
|
802
|
-
```javascript
|
|
803
|
-
const { ErrorFormatter } = require('schema-dsl');
|
|
804
|
-
|
|
805
|
-
const formatter = new ErrorFormatter('zh-CN');
|
|
806
|
-
const errors = formatter.formatDetailed(ajvValidate.errors);
|
|
807
|
-
console.log(errors[0].message);
|
|
808
|
-
```
|
|
809
|
-
|
|
810
|
-
**方法**:
|
|
811
|
-
- `new ErrorFormatter(locale?, messages?)` - 创建错误格式化器
|
|
812
|
-
- `format(error, locale?)` - 格式化单个错误为消息字符串
|
|
813
|
-
- `formatDetailed(errors, locale?, customMessages?, alreadyMerged?)` - 格式化错误数组为标准错误项列表
|
|
814
|
-
|
|
815
|
-
---
|
|
816
|
-
|
|
817
|
-
### MessageTemplate
|
|
818
|
-
|
|
819
|
-
错误消息模板封装类,内部委托 `renderTemplate()` 执行占位符替换。
|
|
820
|
-
|
|
821
|
-
```javascript
|
|
822
|
-
const { MessageTemplate } = require('schema-dsl');
|
|
823
|
-
|
|
824
|
-
const template = new MessageTemplate('{{#label}} is required');
|
|
825
|
-
console.log(template.render({ label: 'Email' }));
|
|
826
|
-
```
|
|
827
|
-
|
|
828
|
-
**方法**:
|
|
829
|
-
- `new MessageTemplate(template)` - 创建模板实例
|
|
830
|
-
- `render(context)` - 渲染当前模板
|
|
831
|
-
- `MessageTemplate.render(template, context)` - 静态快速渲染
|
|
832
|
-
- `MessageTemplate.renderBatch(templates, context)` - 批量渲染多个模板
|
|
833
|
-
|
|
834
|
-
---
|
|
835
|
-
|
|
836
|
-
### renderTemplate(template, params)
|
|
837
|
-
|
|
838
|
-
底层模板渲染函数,同时兼容 `{{#key}}` 和 `{key}` 两种占位符格式。
|
|
839
|
-
|
|
840
|
-
```javascript
|
|
841
|
-
const { renderTemplate } = require('schema-dsl');
|
|
842
|
-
|
|
843
|
-
const msg = renderTemplate('{field} must be {min}~{max}', {
|
|
844
|
-
field: 'age',
|
|
845
|
-
min: 18,
|
|
846
|
-
max: 65,
|
|
847
|
-
});
|
|
848
|
-
|
|
849
|
-
console.log(msg); // age must be 18~65
|
|
850
|
-
```
|
|
851
|
-
|
|
852
|
-
---
|
|
853
|
-
|
|
854
|
-
### JSONSchemaCore
|
|
855
|
-
|
|
856
|
-
`JSONSchemaCore` 是 v1 兼容外观类,用于以链式方式构建 JSON Schema,并可直接调用 `validate()` 做快速校验。
|
|
857
|
-
|
|
858
|
-
```javascript
|
|
859
|
-
const { JSONSchemaCore } = require('schema-dsl');
|
|
860
|
-
|
|
861
|
-
const schema = new JSONSchemaCore()
|
|
862
|
-
.type('object')
|
|
863
|
-
.property('email', { type: 'string', format: 'email' })
|
|
864
|
-
.required('email')
|
|
865
|
-
.getSchema();
|
|
866
|
-
```
|
|
867
|
-
|
|
868
|
-
**常用方法**:
|
|
869
|
-
- `type(typeName)`
|
|
870
|
-
- `property(name, schema)`
|
|
871
|
-
- `properties(properties)`
|
|
872
|
-
- `required(fields)`
|
|
873
|
-
- `format(formatName)`
|
|
874
|
-
- `pattern(pattern)`
|
|
875
|
-
- `items(schema)`
|
|
876
|
-
- `toSchema()` / `getSchema()`
|
|
877
|
-
- `validate(data)`
|
|
878
|
-
|
|
879
|
-
---
|
|
880
|
-
|
|
881
|
-
### 类型注册与内部解析边界
|
|
882
|
-
|
|
883
|
-
`schema-dsl` 的 root API 只保留业务可依赖的稳定入口。DSL 解析器、约束解析器、Schema 编译器和 Adapter 属于内部实现细节,不再作为 root API 文档化导出;业务代码应优先使用 `dsl()`、`DslBuilder`、`Validator` 和 `validate()`。
|
|
884
|
-
|
|
885
|
-
#### TypeRegistry
|
|
886
|
-
|
|
887
|
-
统一类型注册表。它是自定义类型扩展的公开入口;如果只需要注册 DSL 类型,也可以优先使用更高层的 `DslBuilder.registerType()`。
|
|
888
|
-
|
|
889
|
-
- `TypeRegistry.resolve(typeName)`
|
|
890
|
-
- `TypeRegistry.register(name, def)`
|
|
891
|
-
- `TypeRegistry.registerDynamic(name, factory)`
|
|
892
|
-
- `TypeRegistry.unregister(name)`
|
|
893
|
-
- `TypeRegistry.has(typeName)`
|
|
894
|
-
- `TypeRegistry.getInternalKeys()`
|
|
895
|
-
- `TypeRegistry.toJsonSchema(schema)`
|
|
896
|
-
- `TypeRegistry.clearCustomTypes()` — 清空所有自定义类型(含通过 `DslAdapter.registerType()` 注册的类型),适合测试后清理状态
|
|
897
|
-
- `TypeRegistry.setStrict(flag)` — 设置严格模式,等效于 `dsl.config({ strict: flag })`
|
|
898
|
-
|
|
899
|
-
---
|
|
900
|
-
|
|
901
|
-
## DSL 语法快速参考
|
|
902
|
-
|
|
903
|
-
### 基本类型
|
|
904
|
-
|
|
905
|
-
```text
|
|
906
|
-
string, number, integer, boolean
|
|
907
|
-
email, url, uuid, date, datetime
|
|
908
|
-
```
|
|
909
|
-
|
|
910
|
-
### 约束
|
|
911
|
-
|
|
912
|
-
```text
|
|
913
|
-
string:N # 精确长度(exactLength = N,等同于 minLength: N, maxLength: N)
|
|
914
|
-
string:min-max # 字符串长度范围
|
|
915
|
-
number:min-max # 数字范围
|
|
916
|
-
value1|value2 # 枚举
|
|
917
|
-
! # 必填
|
|
918
|
-
```
|
|
919
|
-
|
|
920
|
-
### 数组
|
|
921
|
-
|
|
922
|
-
```text
|
|
923
|
-
array<type> # 数组
|
|
924
|
-
array<string:1-50> # 带约束的数组元素
|
|
925
|
-
```
|
|
926
|
-
|
|
927
|
-
### 示例
|
|
928
|
-
|
|
929
|
-
```javascript
|
|
930
|
-
'string:3-32!' // 必填字符串,长度3-32
|
|
931
|
-
'email!' // 必填邮箱
|
|
932
|
-
'number:18-120' // 可选数字,范围18-120
|
|
933
|
-
'active|inactive|pending' // 枚举
|
|
934
|
-
'array<string:1-20>' // 字符串数组
|
|
935
|
-
```
|
|
936
|
-
|
|
937
|
-
---
|
|
938
|
-
|
|
939
|
-
## 常量
|
|
940
|
-
|
|
941
|
-
### ErrorCodes
|
|
942
|
-
|
|
943
|
-
错误代码常量。
|
|
944
|
-
|
|
945
|
-
```javascript
|
|
946
|
-
const { ErrorCodes } = require('schema-dsl');
|
|
947
|
-
|
|
948
|
-
console.log(ErrorCodes.STRING_MIN); // 'string.min'
|
|
949
|
-
console.log(ErrorCodes.NUMBER_RANGE); // 'number.range'
|
|
950
|
-
```
|
|
951
|
-
|
|
952
|
-
---
|
|
953
|
-
|
|
954
|
-
### Locale
|
|
955
|
-
|
|
956
|
-
多语言支持。
|
|
957
|
-
|
|
958
|
-
```javascript
|
|
959
|
-
const { Locale } = require('schema-dsl');
|
|
960
|
-
|
|
961
|
-
Locale.setLocale('zh-CN'); // 设置中文
|
|
962
|
-
Locale.setLocale('en-US'); // 设置英文
|
|
963
|
-
```
|
|
964
|
-
|
|
965
|
-
---
|
|
966
|
-
|
|
967
|
-
### ConditionalBuilder
|
|
968
|
-
|
|
969
|
-
`dsl.if(conditionFn)` 返回的链式条件构建器,适用于运行时动态条件校验。
|
|
970
|
-
|
|
971
|
-
**常用方法**:
|
|
972
|
-
- `if(condition)`
|
|
973
|
-
- `and(condition)`
|
|
974
|
-
- `or(condition)`
|
|
975
|
-
- `elseIf(condition)`
|
|
976
|
-
- `message(msg)`
|
|
977
|
-
- `then(schema)`
|
|
978
|
-
- `else(schema)`
|
|
979
|
-
- `toSchema()`
|
|
980
|
-
- `build()` - `toSchema()` 的别名
|
|
981
|
-
- `validate(data, options?)`
|
|
982
|
-
- `validateAsync(data, options?)`
|
|
983
|
-
- `assert(data, options?)`
|
|
984
|
-
- `check(data)`
|
|
985
|
-
|
|
986
|
-
更完整的示例和行为说明请参考 [conditional-api.md](./conditional-api.md)。
|
|
987
|
-
|
|
988
|
-
---
|
|
989
|
-
|
|
990
|
-
## 完整示例
|
|
991
|
-
|
|
992
|
-
```javascript
|
|
993
|
-
const { dsl, Validator } = require('schema-dsl');
|
|
994
|
-
|
|
995
|
-
// 定义Schema(使用String扩展)
|
|
996
|
-
const userSchema = dsl({
|
|
997
|
-
username: 'string:3-32!'
|
|
998
|
-
.pattern(/^[a-zA-Z0-9_]+$/)
|
|
999
|
-
.messages({
|
|
1000
|
-
'string.pattern': '只能包含字母、数字和下划线'
|
|
1001
|
-
})
|
|
1002
|
-
.label('用户名'),
|
|
1003
|
-
|
|
1004
|
-
email: 'email!'
|
|
1005
|
-
.label('邮箱地址'),
|
|
1006
|
-
|
|
1007
|
-
password: 'string:8-64!'
|
|
1008
|
-
.pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/)
|
|
1009
|
-
.label('密码'),
|
|
1010
|
-
|
|
1011
|
-
age: 'number:18-120',
|
|
1012
|
-
role: 'user|admin|moderator'
|
|
1013
|
-
});
|
|
1014
|
-
|
|
1015
|
-
// 验证数据
|
|
1016
|
-
const validator = new Validator();
|
|
1017
|
-
const result = validator.validate(userSchema, {
|
|
1018
|
-
username: 'john_doe',
|
|
1019
|
-
email: 'john@example.com',
|
|
1020
|
-
password: 'Password123',
|
|
1021
|
-
age: 25,
|
|
1022
|
-
role: 'user'
|
|
1023
|
-
});
|
|
1024
|
-
|
|
1025
|
-
console.log(result.valid); // true
|
|
1026
|
-
```
|
|
1027
|
-
|
|
1028
|
-
---
|
|
1029
|
-
|
|
1030
|
-
## 更多资源
|
|
1031
|
-
|
|
1032
|
-
- [DSL 语法完整指南](./dsl-syntax.md)
|
|
1033
|
-
- [错误处理](./error-handling.md)
|
|
1034
|
-
- [示例代码](https://github.com/vextjs/schema-dsl/blob/main/examples/docs/api-reference.ts)
|
|
1035
|
-
- [GitHub](https://github.com/vextjs/schema-dsl)
|
|
1036
|
-
|
|
1037
|
-
---
|
|
1038
|
-
|
|
1039
|
-
## 对应示例文件
|
|
1040
|
-
|
|
1041
|
-
**示例入口**: [api-reference.ts](https://github.com/vextjs/schema-dsl/blob/main/examples/docs/api-reference.ts)
|
|
1042
|
-
**说明**: 覆盖 `dsl()`、`validate()`、`validateAsync()`、默认 `Validator` 单例、模板渲染、`JSONSchemaCore`、`ErrorFormatter` 以及底层解析 / 编译工具的可运行调用链。
|
|
1043
|
-
|
|
1044
|
-
---
|
|
1045
|
-
|
|
1046
|
-
**最后更新**: 2026-05-08
|
|
1047
|
-
|
|
1
|
+
# schema-dsl API 参考文档
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
> **更新时间**: 2026-05-22
|
|
5
|
+
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## 📑 目录
|
|
9
|
+
|
|
10
|
+
- [dsl() 函数](#dsl-函数)
|
|
11
|
+
- [DslBuilder 类](#dslbuilder-类)
|
|
12
|
+
- [String 扩展](#string-扩展)
|
|
13
|
+
- [Validator 类](#validator-类)
|
|
14
|
+
- [导出器](#导出器)
|
|
15
|
+
- [工具函数](#工具函数)
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
## dsl() 函数
|
|
20
|
+
|
|
21
|
+
### 描述
|
|
22
|
+
|
|
23
|
+
DSL 主入口函数,支持字符串和对象两种定义方式。
|
|
24
|
+
|
|
25
|
+
### 语法
|
|
26
|
+
|
|
27
|
+
```javascript
|
|
28
|
+
dsl(definition: string | object): DslBuilder | JSONSchema
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
### 参数
|
|
32
|
+
|
|
33
|
+
- `definition` (**string** | **object**) - DSL定义
|
|
34
|
+
- 字符串:返回 DslBuilder 实例(可链式调用)
|
|
35
|
+
- 对象:返回 JSON Schema 对象
|
|
36
|
+
|
|
37
|
+
### 返回值
|
|
38
|
+
|
|
39
|
+
- **DslBuilder** - 当参数为字符串时
|
|
40
|
+
- **Object** - 当参数为对象时(JSON Schema)
|
|
41
|
+
|
|
42
|
+
### 示例
|
|
43
|
+
|
|
44
|
+
```javascript
|
|
45
|
+
// 字符串:返回 DslBuilder
|
|
46
|
+
const builder = dsl('email!');
|
|
47
|
+
builder.pattern(/custom/).label('邮箱');
|
|
48
|
+
|
|
49
|
+
// 对象:返回 JSON Schema
|
|
50
|
+
const schema = dsl({
|
|
51
|
+
username: 'string:3-32!',
|
|
52
|
+
email: 'email!'
|
|
53
|
+
});
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
---
|
|
57
|
+
|
|
58
|
+
## DslBuilder 类
|
|
59
|
+
|
|
60
|
+
### 描述
|
|
61
|
+
|
|
62
|
+
Schema 构建器类,支持链式调用添加验证规则。
|
|
63
|
+
|
|
64
|
+
### 构造函数
|
|
65
|
+
|
|
66
|
+
```javascript
|
|
67
|
+
new DslBuilder(dslString: string)
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
**参数**:
|
|
71
|
+
- `dslString` (**string**) - DSL字符串,如 `'string:3-32!'`
|
|
72
|
+
|
|
73
|
+
### 方法
|
|
74
|
+
|
|
75
|
+
#### `.pattern(regex, message?)`
|
|
76
|
+
|
|
77
|
+
添加正则表达式验证。
|
|
78
|
+
|
|
79
|
+
**参数**:
|
|
80
|
+
- `regex` (**RegExp** | **string**) - 正则表达式
|
|
81
|
+
- `message` (**string**, 可选) - 自定义错误消息
|
|
82
|
+
|
|
83
|
+
**返回**: **DslBuilder**
|
|
84
|
+
|
|
85
|
+
**示例**:
|
|
86
|
+
```javascript
|
|
87
|
+
dsl('string:3-32!')
|
|
88
|
+
.pattern(/^[a-zA-Z0-9_]+$/, '只能包含字母、数字和下划线')
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
---
|
|
92
|
+
|
|
93
|
+
#### `.label(text)`
|
|
94
|
+
|
|
95
|
+
设置字段标签(用于错误消息)。
|
|
96
|
+
|
|
97
|
+
**参数**:
|
|
98
|
+
- `text` (**string**) - 标签文本
|
|
99
|
+
|
|
100
|
+
**返回**: **DslBuilder**
|
|
101
|
+
|
|
102
|
+
**示例**:
|
|
103
|
+
```javascript
|
|
104
|
+
dsl('email!').label('邮箱地址')
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
---
|
|
108
|
+
|
|
109
|
+
#### `.messages(messages)`
|
|
110
|
+
|
|
111
|
+
自定义错误消息。
|
|
112
|
+
|
|
113
|
+
**参数**:
|
|
114
|
+
- `messages` (**Object**) - 错误消息对象
|
|
115
|
+
- 键:错误代码(如 `'string.min'`)
|
|
116
|
+
- 值:错误消息模板
|
|
117
|
+
|
|
118
|
+
**返回**: **DslBuilder**
|
|
119
|
+
|
|
120
|
+
**示例**:
|
|
121
|
+
```javascript
|
|
122
|
+
dsl('string:3-32!')
|
|
123
|
+
.messages({
|
|
124
|
+
'min': '至少{{#limit}}个字符',
|
|
125
|
+
'max': '最多{{#limit}}个字符'
|
|
126
|
+
})
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
---
|
|
130
|
+
|
|
131
|
+
#### `.description(text)`
|
|
132
|
+
|
|
133
|
+
设置字段描述。
|
|
134
|
+
|
|
135
|
+
**参数**:
|
|
136
|
+
- `text` (**string**) - 描述文本
|
|
137
|
+
|
|
138
|
+
**返回**: **DslBuilder**
|
|
139
|
+
|
|
140
|
+
**示例**:
|
|
141
|
+
```javascript
|
|
142
|
+
dsl('url').description('个人主页链接')
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
---
|
|
146
|
+
|
|
147
|
+
#### `.custom(validator)`
|
|
148
|
+
|
|
149
|
+
添加自定义验证器。
|
|
150
|
+
|
|
151
|
+
**参数**:
|
|
152
|
+
- `validator` (**Function**) - 验证函数
|
|
153
|
+
- 签名:`(value) => boolean | string | { error, message } | void`
|
|
154
|
+
- 返回 `true` 表示通过
|
|
155
|
+
- 返回 `false`、错误消息字符串或错误对象表示失败
|
|
156
|
+
- 同步验证器由 `validate()` 和 `validateAsync()` 均执行;异步验证器(返回 `Promise`)仅由 `validateAsync()` 执行,`validate()` 调用时会跳过异步 validator
|
|
157
|
+
|
|
158
|
+
**返回**: **DslBuilder**
|
|
159
|
+
|
|
160
|
+
**示例**:
|
|
161
|
+
```javascript
|
|
162
|
+
dsl('string:3-32!')
|
|
163
|
+
.custom((value) => {
|
|
164
|
+
if (value === 'admin') {
|
|
165
|
+
return { error: 'username.exists', message: '用户名已存在' };
|
|
166
|
+
}
|
|
167
|
+
})
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
---
|
|
172
|
+
|
|
173
|
+
#### `.default(value)`
|
|
174
|
+
|
|
175
|
+
设置默认值。
|
|
176
|
+
|
|
177
|
+
**参数**:
|
|
178
|
+
- `value` (**any**) - 默认值
|
|
179
|
+
|
|
180
|
+
**返回**: **DslBuilder**
|
|
181
|
+
|
|
182
|
+
**示例**:
|
|
183
|
+
```javascript
|
|
184
|
+
dsl('string').default('guest')
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
---
|
|
188
|
+
|
|
189
|
+
#### `.username(preset?)`
|
|
190
|
+
|
|
191
|
+
用户名验证(自动设置长度和正则)。
|
|
192
|
+
|
|
193
|
+
**参数**:
|
|
194
|
+
- `preset` (**string** | **Object**, 可选) - 预设配置
|
|
195
|
+
- 字符串:`'short'` | `'medium'` | `'long'` | `'5-20'`
|
|
196
|
+
- 对象:`{ minLength, maxLength, allowUnderscore, allowNumber }`
|
|
197
|
+
- 默认值:`'medium'` (3-32位)
|
|
198
|
+
|
|
199
|
+
**返回**: **DslBuilder**
|
|
200
|
+
|
|
201
|
+
**示例**:
|
|
202
|
+
```javascript
|
|
203
|
+
// 默认 medium (3-32位)
|
|
204
|
+
dsl('string!').username()
|
|
205
|
+
|
|
206
|
+
// 自定义范围
|
|
207
|
+
dsl('string!').username('5-20')
|
|
208
|
+
|
|
209
|
+
// 使用预设
|
|
210
|
+
dsl('string!').username('short') // 3-16位
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
---
|
|
214
|
+
|
|
215
|
+
#### `.password(strength?)`
|
|
216
|
+
|
|
217
|
+
密码强度验证(自动设置长度和正则)。
|
|
218
|
+
|
|
219
|
+
**参数**:
|
|
220
|
+
- `strength` (**string**, 可选) - 强度级别
|
|
221
|
+
- `'weak'` - 最少6位
|
|
222
|
+
- `'medium'` - 8位,字母+数字(默认)
|
|
223
|
+
- `'strong'` - 8位,大小写+数字
|
|
224
|
+
- `'veryStrong'` - 10位,大小写+数字+特殊字符
|
|
225
|
+
|
|
226
|
+
**返回**: **DslBuilder**
|
|
227
|
+
|
|
228
|
+
**示例**:
|
|
229
|
+
```javascript
|
|
230
|
+
dsl('string!').password('strong')
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
---
|
|
234
|
+
|
|
235
|
+
#### `.phone(country?)`
|
|
236
|
+
|
|
237
|
+
手机号验证(自动设置长度和正则)。
|
|
238
|
+
|
|
239
|
+
**参数**:
|
|
240
|
+
- `country` (**string**, 可选) - 国家代码
|
|
241
|
+
- `'cn'` - 中国(默认)
|
|
242
|
+
- `'us'` - 美国
|
|
243
|
+
- `'uk'` - 英国
|
|
244
|
+
- `'hk'` - 香港
|
|
245
|
+
- `'tw'` - 台湾
|
|
246
|
+
- `'international'` - 国际格式
|
|
247
|
+
|
|
248
|
+
**返回**: **DslBuilder**
|
|
249
|
+
|
|
250
|
+
**注意**: 自动将类型纠正为 `string`(即使写成 `number` 也会自动修正)
|
|
251
|
+
|
|
252
|
+
**示例**:
|
|
253
|
+
```javascript
|
|
254
|
+
// 推荐写法
|
|
255
|
+
dsl('string!').phone('cn')
|
|
256
|
+
|
|
257
|
+
// 自动纠正:number → string
|
|
258
|
+
dsl('number!').phone('cn') // 自动纠正为 string
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
---
|
|
262
|
+
|
|
263
|
+
#### `.toSchema()`
|
|
264
|
+
|
|
265
|
+
转换为 JSON Schema 对象(含内部标记)。
|
|
266
|
+
|
|
267
|
+
**返回**: **Object** - JSON Schema 对象(包含 `_required`、`_customMessages`、`_label` 等 schema-dsl 内部字段)
|
|
268
|
+
|
|
269
|
+
**示例**:
|
|
270
|
+
```javascript
|
|
271
|
+
const schema = dsl('email!').label('邮箱').toSchema();
|
|
272
|
+
// { type: 'string', format: 'email', _label: '邮箱', _required: true }
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
---
|
|
276
|
+
|
|
277
|
+
#### `.toJsonSchema()` <sup>v1.2.5+</sup>
|
|
278
|
+
|
|
279
|
+
转换为纯净的 JSON Schema 对象(无内部标记)。
|
|
280
|
+
|
|
281
|
+
与 `toSchema()` 不同,`toJsonSchema()` 会自动清理所有 schema-dsl 内部标记:
|
|
282
|
+
- **下划线前缀字段**:`_required`、`_customMessages`、`_label`、`_customValidators`、`_whenConditions`
|
|
283
|
+
- **自定义验证关键字(直接清除)**:`alphanum`、`lowercase`、`uppercase`、`trim`、`jsonString`、`port`、`requiredAll`、`strictSchema`、`noSparse`、`includesRequired`、`dateFormat`、`dateGreater`、`dateLess`、`precision`
|
|
284
|
+
- **`exactLength` 特殊翻译**:不直接清除,而是转换为标准 JSON Schema `{ minLength: N, maxLength: N }`(与 v1 DslBuilder `string:N` 行为兼容)
|
|
285
|
+
|
|
286
|
+
> ⚠️ `multipleOf` 是标准 JSON Schema 字段,**不会**被清除(v2 修复了 v1 的错误行为)。
|
|
287
|
+
|
|
288
|
+
返回的对象可直接嵌入 OpenAPI / JSON Schema 等标准文档中,无需下游再做清理。
|
|
289
|
+
|
|
290
|
+
**返回**: **Object** - 纯净的 JSON Schema 对象
|
|
291
|
+
|
|
292
|
+
**适用场景**:
|
|
293
|
+
- 生成 OpenAPI 文档
|
|
294
|
+
- 导出给外部系统消费
|
|
295
|
+
- 任何需要标准 JSON Schema 的场景
|
|
296
|
+
|
|
297
|
+
**示例**:
|
|
298
|
+
```javascript
|
|
299
|
+
// 对比 toSchema() 与 toJsonSchema()
|
|
300
|
+
const builder = dsl('string:3-32!').label('用户名').messages({ min: '至少3个字符' });
|
|
301
|
+
|
|
302
|
+
builder.toSchema();
|
|
303
|
+
// { type: 'string', minLength: 3, maxLength: 32, _required: true, _label: '用户名', _customMessages: { min: '至少3个字符' } }
|
|
304
|
+
|
|
305
|
+
builder.toJsonSchema();
|
|
306
|
+
// { type: 'string', minLength: 3, maxLength: 32 }
|
|
307
|
+
// 注意:不含 _required、_label、_customMessages 等内部字段
|
|
308
|
+
|
|
309
|
+
// string:N 单值语法(exactLength → minLength + maxLength)
|
|
310
|
+
const exact = dsl('string:6!');
|
|
311
|
+
exact.toSchema();
|
|
312
|
+
// { type: 'string', exactLength: 6, _required: true }
|
|
313
|
+
exact.toJsonSchema();
|
|
314
|
+
// { type: 'string', minLength: 6, maxLength: 6 }
|
|
315
|
+
// 注:exactLength 自动翻译为标准 JSON Schema 的 minLength + maxLength(v1 兼容行为)
|
|
316
|
+
|
|
317
|
+
// enum 示例
|
|
318
|
+
const enumBuilder = dsl('enum:admin,user,guest!');
|
|
319
|
+
enumBuilder.toJsonSchema();
|
|
320
|
+
// { type: 'string', enum: ['admin', 'user', 'guest'] }
|
|
321
|
+
|
|
322
|
+
// 用于 OpenAPI 文档生成
|
|
323
|
+
const schema = dsl({
|
|
324
|
+
username: 'string:3-32!',
|
|
325
|
+
email: 'email!',
|
|
326
|
+
age: 'number:0-120'
|
|
327
|
+
});
|
|
328
|
+
// 遍历各字段调用 toJsonSchema() 即可获得标准 JSON Schema
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
---
|
|
332
|
+
|
|
333
|
+
#### `.validate(data)`
|
|
334
|
+
|
|
335
|
+
验证数据(便捷方法)。
|
|
336
|
+
|
|
337
|
+
**参数**:
|
|
338
|
+
- `data` (**any**) - 待验证数据
|
|
339
|
+
|
|
340
|
+
**返回**: **Promise<Object>** - 验证结果
|
|
341
|
+
- `valid` (**boolean**) - 是否通过
|
|
342
|
+
- `errors` (**Array**, 可选) - 错误列表
|
|
343
|
+
- `data` (**any**, 可选) - 验证通过的数据
|
|
344
|
+
|
|
345
|
+
**示例**:
|
|
346
|
+
```javascript
|
|
347
|
+
const result = await dsl('email!').validate('user@example.com');
|
|
348
|
+
console.log(result.valid); // true
|
|
349
|
+
```
|
|
350
|
+
|
|
351
|
+
---
|
|
352
|
+
|
|
353
|
+
### 静态方法
|
|
354
|
+
|
|
355
|
+
#### `dsl.match(field, map)```
|
|
356
|
+
|
|
357
|
+
创建条件验证规则(类似 switch-case)。
|
|
358
|
+
|
|
359
|
+
**参数**:
|
|
360
|
+
- `field` (**string**) - 依赖的字段名
|
|
361
|
+
- `map` (**Object**) - 值与Schema的映射
|
|
362
|
+
- `[value: string]`: 对应的Schema
|
|
363
|
+
- `_default` (**optional**): 默认Schema
|
|
364
|
+
|
|
365
|
+
**返回**: **Object** - 内部Match结构
|
|
366
|
+
|
|
367
|
+
**示例**:
|
|
368
|
+
```javascript
|
|
369
|
+
dsl.match('type', {
|
|
370
|
+
email: 'email!',
|
|
371
|
+
phone: 'string:11!',
|
|
372
|
+
_default: 'string'
|
|
373
|
+
})
|
|
374
|
+
```
|
|
375
|
+
|
|
376
|
+
#### `dsl.if(condition, thenSchema, elseSchema)`
|
|
377
|
+
|
|
378
|
+
创建简单的条件验证规则。
|
|
379
|
+
|
|
380
|
+
**参数**:
|
|
381
|
+
- `condition` (**string**) - 条件字段名
|
|
382
|
+
- `thenSchema` (**string|Object**) - 满足条件时的Schema
|
|
383
|
+
- `elseSchema` (**string|Object**, 可选) - 不满足条件时的Schema
|
|
384
|
+
|
|
385
|
+
**返回**: **Object** - 内部If结构
|
|
386
|
+
|
|
387
|
+
**示例**:
|
|
388
|
+
```javascript
|
|
389
|
+
dsl.if('isVip', 'number:0-50', 'number:0-10')
|
|
390
|
+
```
|
|
391
|
+
|
|
392
|
+
---
|
|
393
|
+
|
|
394
|
+
## 运行时辅助函数
|
|
395
|
+
|
|
396
|
+
### `dsl.config(options)`
|
|
397
|
+
|
|
398
|
+
全局配置入口,在应用启动时调用一次,设置 i18n、缓存、自定义正则和严格类型解析模式。
|
|
399
|
+
|
|
400
|
+
```javascript
|
|
401
|
+
const { dsl } = require('schema-dsl');
|
|
402
|
+
|
|
403
|
+
dsl.config({
|
|
404
|
+
// i18n:内置语言包路径 / 内联 locale bundle / { localesPath } / { locales }
|
|
405
|
+
i18n: './locales',
|
|
406
|
+
|
|
407
|
+
// 默认语言(默认 'en-US')
|
|
408
|
+
defaultLocale: 'zh-CN',
|
|
409
|
+
|
|
410
|
+
// 编译缓存配置
|
|
411
|
+
cache: { maxSize: 2000, ttl: 0, enabled: true },
|
|
412
|
+
|
|
413
|
+
// strict: true → 遇到未知类型直接抛出 Error(默认 false:warn + 回退 string)
|
|
414
|
+
strict: true,
|
|
415
|
+
|
|
416
|
+
// 追加自定义正则规则(phone / idCard / creditCard 等)
|
|
417
|
+
patterns: {
|
|
418
|
+
phone: { us: /^\+1\d{10}$/ }
|
|
419
|
+
}
|
|
420
|
+
});
|
|
421
|
+
```
|
|
422
|
+
|
|
423
|
+
**参数** (`DslConfigOptions`):
|
|
424
|
+
|
|
425
|
+
| 字段 | 类型 | 默认 | 说明 |
|
|
426
|
+
|------|------|------|------|
|
|
427
|
+
| `i18n` | `string \| object` | — | 语言包路径或内联对象 |
|
|
428
|
+
| `defaultLocale` | `string` | `'en-US'` | 默认语言 |
|
|
429
|
+
| `cache` | `CacheOptions` | — | `maxSize` / `ttl` / `enabled` / `statsEnabled` |
|
|
430
|
+
| `strict` | `boolean` | `false` | `true` 时解析未知 DSL 类型抛出 Error |
|
|
431
|
+
| `patterns` | `object` | — | 追加自定义格式正则(phone/idCard/creditCard) |
|
|
432
|
+
|
|
433
|
+
---
|
|
434
|
+
|
|
435
|
+
### `getDefaultValidator()`
|
|
436
|
+
|
|
437
|
+
获取顶层 `validate()` / `validateAsync()` 便捷函数内部复用的默认 `Validator` 单例。
|
|
438
|
+
|
|
439
|
+
```javascript
|
|
440
|
+
const { getDefaultValidator } = require('schema-dsl');
|
|
441
|
+
|
|
442
|
+
const validator = getDefaultValidator();
|
|
443
|
+
console.log(validator.getCacheStats());
|
|
444
|
+
```
|
|
445
|
+
|
|
446
|
+
---
|
|
447
|
+
|
|
448
|
+
### `resetDefaultValidator()`
|
|
449
|
+
|
|
450
|
+
重置顶层 `validate()` / `validateAsync()` 使用的默认 `Validator` 单例。
|
|
451
|
+
|
|
452
|
+
```javascript
|
|
453
|
+
const { resetDefaultValidator } = require('schema-dsl');
|
|
454
|
+
|
|
455
|
+
resetDefaultValidator();
|
|
456
|
+
```
|
|
457
|
+
|
|
458
|
+
---
|
|
459
|
+
|
|
460
|
+
### `installStringExtensions(dslFunction?)`
|
|
461
|
+
|
|
462
|
+
手动安装 String 扩展。模块导入时默认已自动安装;只有在调用过 `uninstallStringExtensions()` 或需要显式恢复扩展时才需要手动执行。
|
|
463
|
+
|
|
464
|
+
```javascript
|
|
465
|
+
const { installStringExtensions } = require('schema-dsl');
|
|
466
|
+
|
|
467
|
+
installStringExtensions();
|
|
468
|
+
```
|
|
469
|
+
|
|
470
|
+
---
|
|
471
|
+
|
|
472
|
+
### `uninstallStringExtensions()`
|
|
473
|
+
|
|
474
|
+
卸载挂载到 `String.prototype` 上的扩展方法。
|
|
475
|
+
|
|
476
|
+
```javascript
|
|
477
|
+
const { uninstallStringExtensions } = require('schema-dsl');
|
|
478
|
+
|
|
479
|
+
uninstallStringExtensions();
|
|
480
|
+
```
|
|
481
|
+
|
|
482
|
+
---
|
|
483
|
+
|
|
484
|
+
## Validator 类
|
|
485
|
+
|
|
486
|
+
**参数**:
|
|
487
|
+
- `options` (**Object**, 可选) - Validator 配置项
|
|
488
|
+
|
|
489
|
+
### 方法
|
|
490
|
+
|
|
491
|
+
#### `.compile(schema, cacheKey?)`
|
|
492
|
+
|
|
493
|
+
编译 Schema 为 AJV 验证函数。
|
|
494
|
+
|
|
495
|
+
**参数**:
|
|
496
|
+
- `schema` (**Object**) - JSON Schema
|
|
497
|
+
- `cacheKey` (**string** | **null**, 可选) - 缓存键
|
|
498
|
+
|
|
499
|
+
**返回**: **Function** - AJV 验证函数
|
|
500
|
+
|
|
501
|
+
**示例**:
|
|
502
|
+
```javascript
|
|
503
|
+
const validator = new Validator();
|
|
504
|
+
const validate = validator.compile(schema, 'user-schema');
|
|
505
|
+
const ok = validate(data);
|
|
506
|
+
```
|
|
507
|
+
|
|
508
|
+
---
|
|
509
|
+
|
|
510
|
+
#### `.validate(schema, data, options?)`
|
|
511
|
+
|
|
512
|
+
同步验证。
|
|
513
|
+
|
|
514
|
+
**参数**:
|
|
515
|
+
- `schema` (**Object** | **Function**) - JSON Schema 或已编译的验证函数
|
|
516
|
+
- `data` (**any**) - 待验证数据
|
|
517
|
+
- `options` (**Object**, 可选) - 验证选项
|
|
518
|
+
|
|
519
|
+
**返回**: **Object**
|
|
520
|
+
- `valid` (**boolean**) - 是否通过
|
|
521
|
+
- `errors` (**Array**, 可选) - 错误列表
|
|
522
|
+
- `data` (**any**, 可选) - 经过处理后的数据
|
|
523
|
+
|
|
524
|
+
**示例**:
|
|
525
|
+
```javascript
|
|
526
|
+
const validator = new Validator();
|
|
527
|
+
const result = validator.validate(schema, payload);
|
|
528
|
+
console.log(result.valid);
|
|
529
|
+
```
|
|
530
|
+
|
|
531
|
+
---
|
|
532
|
+
|
|
533
|
+
#### `.validateAsync(schema, data, options?)`
|
|
534
|
+
|
|
535
|
+
异步验证。验证失败时抛出 `ValidationError`。
|
|
536
|
+
|
|
537
|
+
**参数**:
|
|
538
|
+
- `schema` (**Object** | **Function**) - JSON Schema 或已编译的验证函数
|
|
539
|
+
- `data` (**any**) - 待验证数据
|
|
540
|
+
- `options` (**Object**, 可选) - 验证选项
|
|
541
|
+
|
|
542
|
+
**返回**: **Promise<any>** - 验证通过后的数据
|
|
543
|
+
|
|
544
|
+
**示例**:
|
|
545
|
+
```javascript
|
|
546
|
+
const validator = new Validator();
|
|
547
|
+
await validator.validateAsync(schema, payload);
|
|
548
|
+
```
|
|
549
|
+
|
|
550
|
+
---
|
|
551
|
+
|
|
552
|
+
#### `.validateBatch(schema, dataArray)`
|
|
553
|
+
|
|
554
|
+
批量验证。Schema 只编译一次,多次复用。
|
|
555
|
+
|
|
556
|
+
**参数**:
|
|
557
|
+
- `schema` (**Object**) - JSON Schema
|
|
558
|
+
- `dataArray` (**Array**) - 待验证数据数组
|
|
559
|
+
|
|
560
|
+
**返回**: **Array<Object>** - 每项对应一个验证结果
|
|
561
|
+
|
|
562
|
+
**示例**:
|
|
563
|
+
```javascript
|
|
564
|
+
const validator = new Validator();
|
|
565
|
+
const results = validator.validateBatch(schema, records);
|
|
566
|
+
```
|
|
567
|
+
|
|
568
|
+
---
|
|
569
|
+
|
|
570
|
+
#### `.addKeyword(keyword, definition)`
|
|
571
|
+
|
|
572
|
+
添加 AJV 自定义关键字。
|
|
573
|
+
|
|
574
|
+
**参数**:
|
|
575
|
+
- `keyword` (**string**) - 关键字名称
|
|
576
|
+
- `definition` (**Object**) - AJV 关键字定义
|
|
577
|
+
|
|
578
|
+
**返回**: **Validator**
|
|
579
|
+
|
|
580
|
+
**示例**:
|
|
581
|
+
```javascript
|
|
582
|
+
const validator = new Validator();
|
|
583
|
+
validator.addKeyword('isEven', {
|
|
584
|
+
type: 'number',
|
|
585
|
+
validate: (_schema, data) => data % 2 === 0
|
|
586
|
+
});
|
|
587
|
+
```
|
|
588
|
+
|
|
589
|
+
---
|
|
590
|
+
|
|
591
|
+
#### `.addFormat(name, validator)`
|
|
592
|
+
|
|
593
|
+
添加 AJV 自定义格式。
|
|
594
|
+
|
|
595
|
+
**参数**:
|
|
596
|
+
- `name` (**string**) - 格式名称
|
|
597
|
+
- `validator` (**Function** | **Object**) - AJV format 定义
|
|
598
|
+
|
|
599
|
+
**返回**: **Validator**
|
|
600
|
+
|
|
601
|
+
**示例**:
|
|
602
|
+
```javascript
|
|
603
|
+
const validator = new Validator();
|
|
604
|
+
validator.addFormat('phone-cn', /^1[3-9]\d{9}$/);
|
|
605
|
+
```
|
|
606
|
+
|
|
607
|
+
---
|
|
608
|
+
|
|
609
|
+
#### `.addSchema(uri, schema)`
|
|
610
|
+
|
|
611
|
+
添加 schema 引用。
|
|
612
|
+
|
|
613
|
+
**参数**:
|
|
614
|
+
- `uri` (**string**) - schema 标识
|
|
615
|
+
- `schema` (**Object**) - JSON Schema
|
|
616
|
+
|
|
617
|
+
**返回**: **Validator**
|
|
618
|
+
|
|
619
|
+
**示例**:
|
|
620
|
+
```javascript
|
|
621
|
+
const validator = new Validator();
|
|
622
|
+
validator.addSchema('user.schema.json', schema);
|
|
623
|
+
```
|
|
624
|
+
|
|
625
|
+
---
|
|
626
|
+
|
|
627
|
+
#### `.removeSchema(uri)`
|
|
628
|
+
|
|
629
|
+
删除 schema 引用。
|
|
630
|
+
|
|
631
|
+
**参数**:
|
|
632
|
+
- `uri` (**string**) - schema 标识
|
|
633
|
+
|
|
634
|
+
**返回**: **Validator**
|
|
635
|
+
|
|
636
|
+
**示例**:
|
|
637
|
+
```javascript
|
|
638
|
+
const validator = new Validator();
|
|
639
|
+
validator.removeSchema('user.schema.json');
|
|
640
|
+
```
|
|
641
|
+
|
|
642
|
+
---
|
|
643
|
+
|
|
644
|
+
#### `.getAjv()`
|
|
645
|
+
|
|
646
|
+
获取底层 AJV 实例。
|
|
647
|
+
|
|
648
|
+
**返回**: **Ajv**
|
|
649
|
+
|
|
650
|
+
**示例**:
|
|
651
|
+
```javascript
|
|
652
|
+
const validator = new Validator();
|
|
653
|
+
const ajv = validator.getAjv();
|
|
654
|
+
```
|
|
655
|
+
|
|
656
|
+
---
|
|
657
|
+
|
|
658
|
+
#### `.clearCache()`
|
|
659
|
+
|
|
660
|
+
清空编译缓存。
|
|
661
|
+
|
|
662
|
+
**返回**: `void`
|
|
663
|
+
|
|
664
|
+
**示例**:
|
|
665
|
+
```javascript
|
|
666
|
+
const validator = new Validator();
|
|
667
|
+
validator.clearCache();
|
|
668
|
+
```
|
|
669
|
+
|
|
670
|
+
---
|
|
671
|
+
|
|
672
|
+
#### `.getCacheStats()`
|
|
673
|
+
|
|
674
|
+
获取缓存统计信息。
|
|
675
|
+
|
|
676
|
+
**返回**: **Object**
|
|
677
|
+
|
|
678
|
+
**示例**:
|
|
679
|
+
```javascript
|
|
680
|
+
const validator = new Validator();
|
|
681
|
+
console.log(validator.getCacheStats());
|
|
682
|
+
```
|
|
683
|
+
|
|
684
|
+
---
|
|
685
|
+
|
|
686
|
+
### 静态方法
|
|
687
|
+
|
|
688
|
+
#### `Validator.create(options?)`
|
|
689
|
+
|
|
690
|
+
创建 `Validator` 实例。
|
|
691
|
+
|
|
692
|
+
**返回**: **Validator**
|
|
693
|
+
|
|
694
|
+
**示例**:
|
|
695
|
+
```javascript
|
|
696
|
+
const validator = Validator.create();
|
|
697
|
+
```
|
|
698
|
+
|
|
699
|
+
---
|
|
700
|
+
|
|
701
|
+
#### `Validator.quickValidate(schema, data)`
|
|
702
|
+
|
|
703
|
+
快速验证。
|
|
704
|
+
|
|
705
|
+
**参数**:
|
|
706
|
+
- `schema` (**Object**) - JSON Schema
|
|
707
|
+
- `data` (**any**) - 待验证数据
|
|
708
|
+
|
|
709
|
+
**返回**: **boolean**
|
|
710
|
+
|
|
711
|
+
**示例**:
|
|
712
|
+
```javascript
|
|
713
|
+
const ok = Validator.quickValidate(schema, data);
|
|
714
|
+
```
|
|
715
|
+
|
|
716
|
+
---
|
|
717
|
+
|
|
718
|
+
## 导出器
|
|
719
|
+
|
|
720
|
+
### MongoDBExporter
|
|
721
|
+
|
|
722
|
+
导出为 MongoDB 验证Schema。
|
|
723
|
+
|
|
724
|
+
```javascript
|
|
725
|
+
const { MongoDBExporter } = require('schema-dsl');
|
|
726
|
+
|
|
727
|
+
const exporter = new MongoDBExporter({ strict: true });
|
|
728
|
+
const mongoSchema = exporter.export(jsonSchema);
|
|
729
|
+
const command = exporter.generateCommand('users', jsonSchema);
|
|
730
|
+
```
|
|
731
|
+
|
|
732
|
+
**方法**:
|
|
733
|
+
- `export(schema)` - 导出为MongoDB Schema
|
|
734
|
+
- `generateCommand(collection, schema)` - 生成 createCollection 命令
|
|
735
|
+
|
|
736
|
+
---
|
|
737
|
+
|
|
738
|
+
### MySQLExporter
|
|
739
|
+
|
|
740
|
+
导出为 MySQL DDL。
|
|
741
|
+
|
|
742
|
+
```javascript
|
|
743
|
+
const { MySQLExporter } = require('schema-dsl');
|
|
744
|
+
|
|
745
|
+
const exporter = new MySQLExporter();
|
|
746
|
+
const ddl = exporter.export('users', jsonSchema);
|
|
747
|
+
```
|
|
748
|
+
|
|
749
|
+
**方法**:
|
|
750
|
+
- `export(tableName, schema)` - 导出为MySQL DDL
|
|
751
|
+
|
|
752
|
+
---
|
|
753
|
+
|
|
754
|
+
### PostgreSQLExporter
|
|
755
|
+
|
|
756
|
+
导出为 PostgreSQL DDL。
|
|
757
|
+
|
|
758
|
+
```javascript
|
|
759
|
+
const { PostgreSQLExporter } = require('schema-dsl');
|
|
760
|
+
|
|
761
|
+
const exporter = new PostgreSQLExporter();
|
|
762
|
+
const ddl = exporter.export('users', jsonSchema);
|
|
763
|
+
```
|
|
764
|
+
|
|
765
|
+
**方法**:
|
|
766
|
+
- `export(tableName, schema)` - 导出为PostgreSQL DDL
|
|
767
|
+
|
|
768
|
+
---
|
|
769
|
+
|
|
770
|
+
## 工具函数
|
|
771
|
+
|
|
772
|
+
### TypeConverter
|
|
773
|
+
|
|
774
|
+
类型转换工具。
|
|
775
|
+
|
|
776
|
+
```javascript
|
|
777
|
+
const { TypeConverter } = require('schema-dsl');
|
|
778
|
+
|
|
779
|
+
TypeConverter.toJSONSchemaType('string');
|
|
780
|
+
TypeConverter.toMongoDBType('integer');
|
|
781
|
+
```
|
|
782
|
+
|
|
783
|
+
---
|
|
784
|
+
|
|
785
|
+
### SchemaHelper
|
|
786
|
+
|
|
787
|
+
Schema辅助工具。
|
|
788
|
+
|
|
789
|
+
```javascript
|
|
790
|
+
const { SchemaHelper } = require('schema-dsl');
|
|
791
|
+
|
|
792
|
+
SchemaHelper.merge(schema1, schema2);
|
|
793
|
+
SchemaHelper.clone(schema);
|
|
794
|
+
```
|
|
795
|
+
|
|
796
|
+
---
|
|
797
|
+
|
|
798
|
+
### ErrorFormatter
|
|
799
|
+
|
|
800
|
+
验证错误格式化工具,用于把 Ajv 原始错误数组或简化错误对象转换成统一的错误项结构或消息文本。
|
|
801
|
+
|
|
802
|
+
```javascript
|
|
803
|
+
const { ErrorFormatter } = require('schema-dsl');
|
|
804
|
+
|
|
805
|
+
const formatter = new ErrorFormatter('zh-CN');
|
|
806
|
+
const errors = formatter.formatDetailed(ajvValidate.errors);
|
|
807
|
+
console.log(errors[0].message);
|
|
808
|
+
```
|
|
809
|
+
|
|
810
|
+
**方法**:
|
|
811
|
+
- `new ErrorFormatter(locale?, messages?)` - 创建错误格式化器
|
|
812
|
+
- `format(error, locale?)` - 格式化单个错误为消息字符串
|
|
813
|
+
- `formatDetailed(errors, locale?, customMessages?, alreadyMerged?)` - 格式化错误数组为标准错误项列表
|
|
814
|
+
|
|
815
|
+
---
|
|
816
|
+
|
|
817
|
+
### MessageTemplate
|
|
818
|
+
|
|
819
|
+
错误消息模板封装类,内部委托 `renderTemplate()` 执行占位符替换。
|
|
820
|
+
|
|
821
|
+
```javascript
|
|
822
|
+
const { MessageTemplate } = require('schema-dsl');
|
|
823
|
+
|
|
824
|
+
const template = new MessageTemplate('{{#label}} is required');
|
|
825
|
+
console.log(template.render({ label: 'Email' }));
|
|
826
|
+
```
|
|
827
|
+
|
|
828
|
+
**方法**:
|
|
829
|
+
- `new MessageTemplate(template)` - 创建模板实例
|
|
830
|
+
- `render(context)` - 渲染当前模板
|
|
831
|
+
- `MessageTemplate.render(template, context)` - 静态快速渲染
|
|
832
|
+
- `MessageTemplate.renderBatch(templates, context)` - 批量渲染多个模板
|
|
833
|
+
|
|
834
|
+
---
|
|
835
|
+
|
|
836
|
+
### renderTemplate(template, params)
|
|
837
|
+
|
|
838
|
+
底层模板渲染函数,同时兼容 `{{#key}}` 和 `{key}` 两种占位符格式。
|
|
839
|
+
|
|
840
|
+
```javascript
|
|
841
|
+
const { renderTemplate } = require('schema-dsl');
|
|
842
|
+
|
|
843
|
+
const msg = renderTemplate('{field} must be {min}~{max}', {
|
|
844
|
+
field: 'age',
|
|
845
|
+
min: 18,
|
|
846
|
+
max: 65,
|
|
847
|
+
});
|
|
848
|
+
|
|
849
|
+
console.log(msg); // age must be 18~65
|
|
850
|
+
```
|
|
851
|
+
|
|
852
|
+
---
|
|
853
|
+
|
|
854
|
+
### JSONSchemaCore
|
|
855
|
+
|
|
856
|
+
`JSONSchemaCore` 是 v1 兼容外观类,用于以链式方式构建 JSON Schema,并可直接调用 `validate()` 做快速校验。
|
|
857
|
+
|
|
858
|
+
```javascript
|
|
859
|
+
const { JSONSchemaCore } = require('schema-dsl');
|
|
860
|
+
|
|
861
|
+
const schema = new JSONSchemaCore()
|
|
862
|
+
.type('object')
|
|
863
|
+
.property('email', { type: 'string', format: 'email' })
|
|
864
|
+
.required('email')
|
|
865
|
+
.getSchema();
|
|
866
|
+
```
|
|
867
|
+
|
|
868
|
+
**常用方法**:
|
|
869
|
+
- `type(typeName)`
|
|
870
|
+
- `property(name, schema)`
|
|
871
|
+
- `properties(properties)`
|
|
872
|
+
- `required(fields)`
|
|
873
|
+
- `format(formatName)`
|
|
874
|
+
- `pattern(pattern)`
|
|
875
|
+
- `items(schema)`
|
|
876
|
+
- `toSchema()` / `getSchema()`
|
|
877
|
+
- `validate(data)`
|
|
878
|
+
|
|
879
|
+
---
|
|
880
|
+
|
|
881
|
+
### 类型注册与内部解析边界
|
|
882
|
+
|
|
883
|
+
`schema-dsl` 的 root API 只保留业务可依赖的稳定入口。DSL 解析器、约束解析器、Schema 编译器和 Adapter 属于内部实现细节,不再作为 root API 文档化导出;业务代码应优先使用 `dsl()`、`DslBuilder`、`Validator` 和 `validate()`。
|
|
884
|
+
|
|
885
|
+
#### TypeRegistry
|
|
886
|
+
|
|
887
|
+
统一类型注册表。它是自定义类型扩展的公开入口;如果只需要注册 DSL 类型,也可以优先使用更高层的 `DslBuilder.registerType()`。
|
|
888
|
+
|
|
889
|
+
- `TypeRegistry.resolve(typeName)`
|
|
890
|
+
- `TypeRegistry.register(name, def)`
|
|
891
|
+
- `TypeRegistry.registerDynamic(name, factory)`
|
|
892
|
+
- `TypeRegistry.unregister(name)`
|
|
893
|
+
- `TypeRegistry.has(typeName)`
|
|
894
|
+
- `TypeRegistry.getInternalKeys()`
|
|
895
|
+
- `TypeRegistry.toJsonSchema(schema)`
|
|
896
|
+
- `TypeRegistry.clearCustomTypes()` — 清空所有自定义类型(含通过 `DslAdapter.registerType()` 注册的类型),适合测试后清理状态
|
|
897
|
+
- `TypeRegistry.setStrict(flag)` — 设置严格模式,等效于 `dsl.config({ strict: flag })`
|
|
898
|
+
|
|
899
|
+
---
|
|
900
|
+
|
|
901
|
+
## DSL 语法快速参考
|
|
902
|
+
|
|
903
|
+
### 基本类型
|
|
904
|
+
|
|
905
|
+
```text
|
|
906
|
+
string, number, integer, boolean
|
|
907
|
+
email, url, uuid, date, datetime
|
|
908
|
+
```
|
|
909
|
+
|
|
910
|
+
### 约束
|
|
911
|
+
|
|
912
|
+
```text
|
|
913
|
+
string:N # 精确长度(exactLength = N,等同于 minLength: N, maxLength: N)
|
|
914
|
+
string:min-max # 字符串长度范围
|
|
915
|
+
number:min-max # 数字范围
|
|
916
|
+
value1|value2 # 枚举
|
|
917
|
+
! # 必填
|
|
918
|
+
```
|
|
919
|
+
|
|
920
|
+
### 数组
|
|
921
|
+
|
|
922
|
+
```text
|
|
923
|
+
array<type> # 数组
|
|
924
|
+
array<string:1-50> # 带约束的数组元素
|
|
925
|
+
```
|
|
926
|
+
|
|
927
|
+
### 示例
|
|
928
|
+
|
|
929
|
+
```javascript
|
|
930
|
+
'string:3-32!' // 必填字符串,长度3-32
|
|
931
|
+
'email!' // 必填邮箱
|
|
932
|
+
'number:18-120' // 可选数字,范围18-120
|
|
933
|
+
'active|inactive|pending' // 枚举
|
|
934
|
+
'array<string:1-20>' // 字符串数组
|
|
935
|
+
```
|
|
936
|
+
|
|
937
|
+
---
|
|
938
|
+
|
|
939
|
+
## 常量
|
|
940
|
+
|
|
941
|
+
### ErrorCodes
|
|
942
|
+
|
|
943
|
+
错误代码常量。
|
|
944
|
+
|
|
945
|
+
```javascript
|
|
946
|
+
const { ErrorCodes } = require('schema-dsl');
|
|
947
|
+
|
|
948
|
+
console.log(ErrorCodes.STRING_MIN); // 'string.min'
|
|
949
|
+
console.log(ErrorCodes.NUMBER_RANGE); // 'number.range'
|
|
950
|
+
```
|
|
951
|
+
|
|
952
|
+
---
|
|
953
|
+
|
|
954
|
+
### Locale
|
|
955
|
+
|
|
956
|
+
多语言支持。
|
|
957
|
+
|
|
958
|
+
```javascript
|
|
959
|
+
const { Locale } = require('schema-dsl');
|
|
960
|
+
|
|
961
|
+
Locale.setLocale('zh-CN'); // 设置中文
|
|
962
|
+
Locale.setLocale('en-US'); // 设置英文
|
|
963
|
+
```
|
|
964
|
+
|
|
965
|
+
---
|
|
966
|
+
|
|
967
|
+
### ConditionalBuilder
|
|
968
|
+
|
|
969
|
+
`dsl.if(conditionFn)` 返回的链式条件构建器,适用于运行时动态条件校验。
|
|
970
|
+
|
|
971
|
+
**常用方法**:
|
|
972
|
+
- `if(condition)`
|
|
973
|
+
- `and(condition)`
|
|
974
|
+
- `or(condition)`
|
|
975
|
+
- `elseIf(condition)`
|
|
976
|
+
- `message(msg)`
|
|
977
|
+
- `then(schema)`
|
|
978
|
+
- `else(schema)`
|
|
979
|
+
- `toSchema()`
|
|
980
|
+
- `build()` - `toSchema()` 的别名
|
|
981
|
+
- `validate(data, options?)`
|
|
982
|
+
- `validateAsync(data, options?)`
|
|
983
|
+
- `assert(data, options?)`
|
|
984
|
+
- `check(data)`
|
|
985
|
+
|
|
986
|
+
更完整的示例和行为说明请参考 [conditional-api.md](./conditional-api.md)。
|
|
987
|
+
|
|
988
|
+
---
|
|
989
|
+
|
|
990
|
+
## 完整示例
|
|
991
|
+
|
|
992
|
+
```javascript
|
|
993
|
+
const { dsl, Validator } = require('schema-dsl');
|
|
994
|
+
|
|
995
|
+
// 定义Schema(使用String扩展)
|
|
996
|
+
const userSchema = dsl({
|
|
997
|
+
username: 'string:3-32!'
|
|
998
|
+
.pattern(/^[a-zA-Z0-9_]+$/)
|
|
999
|
+
.messages({
|
|
1000
|
+
'string.pattern': '只能包含字母、数字和下划线'
|
|
1001
|
+
})
|
|
1002
|
+
.label('用户名'),
|
|
1003
|
+
|
|
1004
|
+
email: 'email!'
|
|
1005
|
+
.label('邮箱地址'),
|
|
1006
|
+
|
|
1007
|
+
password: 'string:8-64!'
|
|
1008
|
+
.pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/)
|
|
1009
|
+
.label('密码'),
|
|
1010
|
+
|
|
1011
|
+
age: 'number:18-120',
|
|
1012
|
+
role: 'user|admin|moderator'
|
|
1013
|
+
});
|
|
1014
|
+
|
|
1015
|
+
// 验证数据
|
|
1016
|
+
const validator = new Validator();
|
|
1017
|
+
const result = validator.validate(userSchema, {
|
|
1018
|
+
username: 'john_doe',
|
|
1019
|
+
email: 'john@example.com',
|
|
1020
|
+
password: 'Password123',
|
|
1021
|
+
age: 25,
|
|
1022
|
+
role: 'user'
|
|
1023
|
+
});
|
|
1024
|
+
|
|
1025
|
+
console.log(result.valid); // true
|
|
1026
|
+
```
|
|
1027
|
+
|
|
1028
|
+
---
|
|
1029
|
+
|
|
1030
|
+
## 更多资源
|
|
1031
|
+
|
|
1032
|
+
- [DSL 语法完整指南](./dsl-syntax.md)
|
|
1033
|
+
- [错误处理](./error-handling.md)
|
|
1034
|
+
- [示例代码](https://github.com/vextjs/schema-dsl/blob/main/examples/docs/api-reference.ts)
|
|
1035
|
+
- [GitHub](https://github.com/vextjs/schema-dsl)
|
|
1036
|
+
|
|
1037
|
+
---
|
|
1038
|
+
|
|
1039
|
+
## 对应示例文件
|
|
1040
|
+
|
|
1041
|
+
**示例入口**: [api-reference.ts](https://github.com/vextjs/schema-dsl/blob/main/examples/docs/api-reference.ts)
|
|
1042
|
+
**说明**: 覆盖 `dsl()`、`validate()`、`validateAsync()`、默认 `Validator` 单例、模板渲染、`JSONSchemaCore`、`ErrorFormatter` 以及底层解析 / 编译工具的可运行调用链。
|
|
1043
|
+
|
|
1044
|
+
---
|
|
1045
|
+
|
|
1046
|
+
**最后更新**: 2026-05-08
|
|
1047
|
+
|