schema-dsl 1.0.0

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.
Files changed (116) hide show
  1. package/.eslintignore +10 -0
  2. package/.eslintrc.json +27 -0
  3. package/.github/CODE_OF_CONDUCT.md +45 -0
  4. package/.github/ISSUE_TEMPLATE/bug_report.md +57 -0
  5. package/.github/ISSUE_TEMPLATE/config.yml +11 -0
  6. package/.github/ISSUE_TEMPLATE/feature_request.md +45 -0
  7. package/.github/ISSUE_TEMPLATE/question.md +31 -0
  8. package/.github/PULL_REQUEST_TEMPLATE.md +70 -0
  9. package/.github/SECURITY.md +184 -0
  10. package/.github/workflows/ci.yml +33 -0
  11. package/CHANGELOG.md +633 -0
  12. package/CONTRIBUTING.md +368 -0
  13. package/LICENSE +21 -0
  14. package/README.md +1184 -0
  15. package/STATUS.md +101 -0
  16. package/docs/FEATURE-INDEX.md +519 -0
  17. package/docs/INDEX.md +253 -0
  18. package/docs/api-reference.md +1096 -0
  19. package/docs/best-practices.md +672 -0
  20. package/docs/cache-manager.md +336 -0
  21. package/docs/design-philosophy.md +601 -0
  22. package/docs/dsl-syntax.md +653 -0
  23. package/docs/dynamic-locale.md +552 -0
  24. package/docs/error-handling.md +703 -0
  25. package/docs/export-guide.md +462 -0
  26. package/docs/export-limitations.md +551 -0
  27. package/docs/faq.md +577 -0
  28. package/docs/frontend-i18n-guide.md +290 -0
  29. package/docs/i18n-user-guide.md +476 -0
  30. package/docs/label-vs-description.md +262 -0
  31. package/docs/markdown-exporter.md +397 -0
  32. package/docs/mongodb-exporter.md +295 -0
  33. package/docs/multi-type-support.md +319 -0
  34. package/docs/mysql-exporter.md +273 -0
  35. package/docs/plugin-system.md +542 -0
  36. package/docs/postgresql-exporter.md +304 -0
  37. package/docs/quick-start.md +761 -0
  38. package/docs/schema-helper.md +340 -0
  39. package/docs/schema-utils-chaining.md +143 -0
  40. package/docs/schema-utils.md +490 -0
  41. package/docs/string-extensions.md +480 -0
  42. package/docs/troubleshooting.md +471 -0
  43. package/docs/type-converter.md +319 -0
  44. package/docs/type-reference.md +219 -0
  45. package/docs/validate-async.md +480 -0
  46. package/docs/validate.md +486 -0
  47. package/docs/validation-guide.md +484 -0
  48. package/examples/array-dsl-example.js +227 -0
  49. package/examples/custom-extension.js +85 -0
  50. package/examples/dsl-match-example.js +74 -0
  51. package/examples/dsl-style.js +118 -0
  52. package/examples/dynamic-locale-configuration.js +348 -0
  53. package/examples/dynamic-locale-example.js +287 -0
  54. package/examples/export-demo.js +130 -0
  55. package/examples/express-integration.js +376 -0
  56. package/examples/i18n-full-demo.js +310 -0
  57. package/examples/i18n-memory-safety.examples.js +268 -0
  58. package/examples/markdown-export.js +71 -0
  59. package/examples/middleware-usage.js +93 -0
  60. package/examples/new-features-comparison.js +315 -0
  61. package/examples/password-reset/README.md +153 -0
  62. package/examples/password-reset/schema.js +26 -0
  63. package/examples/password-reset/test.js +101 -0
  64. package/examples/plugin-system.examples.js +205 -0
  65. package/examples/schema-utils-chaining.examples.js +250 -0
  66. package/examples/simple-example.js +122 -0
  67. package/examples/string-extensions.js +297 -0
  68. package/examples/user-registration/README.md +156 -0
  69. package/examples/user-registration/routes.js +92 -0
  70. package/examples/user-registration/schema.js +150 -0
  71. package/examples/user-registration/server.js +74 -0
  72. package/index.d.ts +1999 -0
  73. package/index.js +282 -0
  74. package/index.mjs +30 -0
  75. package/lib/adapters/DslAdapter.js +699 -0
  76. package/lib/adapters/index.js +20 -0
  77. package/lib/config/constants.js +286 -0
  78. package/lib/config/patterns/creditCard.js +9 -0
  79. package/lib/config/patterns/idCard.js +9 -0
  80. package/lib/config/patterns/index.js +8 -0
  81. package/lib/config/patterns/licensePlate.js +4 -0
  82. package/lib/config/patterns/passport.js +4 -0
  83. package/lib/config/patterns/phone.js +9 -0
  84. package/lib/config/patterns/postalCode.js +5 -0
  85. package/lib/core/CacheManager.js +376 -0
  86. package/lib/core/DslBuilder.js +740 -0
  87. package/lib/core/ErrorCodes.js +233 -0
  88. package/lib/core/ErrorFormatter.js +342 -0
  89. package/lib/core/JSONSchemaCore.js +347 -0
  90. package/lib/core/Locale.js +119 -0
  91. package/lib/core/MessageTemplate.js +89 -0
  92. package/lib/core/PluginManager.js +448 -0
  93. package/lib/core/StringExtensions.js +209 -0
  94. package/lib/core/Validator.js +376 -0
  95. package/lib/errors/ValidationError.js +191 -0
  96. package/lib/exporters/MarkdownExporter.js +420 -0
  97. package/lib/exporters/MongoDBExporter.js +162 -0
  98. package/lib/exporters/MySQLExporter.js +212 -0
  99. package/lib/exporters/PostgreSQLExporter.js +289 -0
  100. package/lib/exporters/index.js +24 -0
  101. package/lib/locales/en-US.js +65 -0
  102. package/lib/locales/es-ES.js +66 -0
  103. package/lib/locales/fr-FR.js +66 -0
  104. package/lib/locales/index.js +8 -0
  105. package/lib/locales/ja-JP.js +66 -0
  106. package/lib/locales/zh-CN.js +93 -0
  107. package/lib/utils/LRUCache.js +174 -0
  108. package/lib/utils/SchemaHelper.js +240 -0
  109. package/lib/utils/SchemaUtils.js +445 -0
  110. package/lib/utils/TypeConverter.js +245 -0
  111. package/lib/utils/index.js +13 -0
  112. package/lib/validators/CustomKeywords.js +203 -0
  113. package/lib/validators/index.js +11 -0
  114. package/package.json +70 -0
  115. package/plugins/custom-format.js +101 -0
  116. package/plugins/custom-validator.js +200 -0
@@ -0,0 +1,480 @@
1
+ # validateAsync - 异步验证
2
+
3
+ > 验证失败自动抛出错误
4
+
5
+ ---
6
+
7
+ ## 快速开始
8
+
9
+ ```javascript
10
+ const { dsl, validateAsync } = require('schema-dsl');
11
+
12
+ const userSchema = dsl({
13
+ name: 'string!',
14
+ email: 'email!',
15
+ age: 'integer:18-120'
16
+ });
17
+
18
+ try {
19
+ const data = await validateAsync(userSchema, {
20
+ name: 'John',
21
+ email: 'john@example.com',
22
+ age: 30
23
+ });
24
+
25
+ console.log('验证成功:', data);
26
+ } catch (error) {
27
+ console.error('验证失败:', error.message);
28
+ }
29
+ ```
30
+
31
+ ---
32
+
33
+ ## 基础用法
34
+ name: '',
35
+ email: 'invalid'
36
+ });
37
+ } catch (error) {
38
+ console.log(error instanceof ValidationError); // true
39
+ console.log(error.getFieldErrors());
40
+ // { name: '长度必须大于等于1', email: '邮箱格式错误', age: '字段必填' }
41
+ }
42
+ ```
43
+
44
+ ---
45
+
46
+ ## ValidationError
47
+
48
+ ### 属性
49
+
50
+ ```javascript
51
+ class ValidationError extends Error {
52
+ name: 'ValidationError' // 错误名称
53
+ message: string // 友好的错误消息
54
+ errors: Array<Object> // 原始错误列表
55
+ data: any // 原始输入数据
56
+ statusCode: 400 // HTTP 状态码
57
+ }
58
+ ```
59
+
60
+ ### 方法
61
+
62
+ #### 1. `toJSON()` - 转换为 JSON(用于 API 响应)
63
+
64
+ ```javascript
65
+ try {
66
+ await validateAsync(schema, data);
67
+ } catch (error) {
68
+ const json = error.toJSON();
69
+ // {
70
+ // error: 'ValidationError',
71
+ // message: 'Validation failed: name: 字段必填',
72
+ // statusCode: 400,
73
+ // details: [
74
+ // { field: 'name', message: '字段必填', keyword: 'required', params: {...} }
75
+ // ]
76
+ // }
77
+ }
78
+ ```
79
+
80
+ #### 2. `getFieldError(field)` - 获取指定字段的错误
81
+
82
+ ```javascript
83
+ try {
84
+ await validateAsync(schema, data);
85
+ } catch (error) {
86
+ const nameError = error.getFieldError('name');
87
+ console.log(nameError.message); // '字段必填'
88
+ }
89
+ ```
90
+
91
+ #### 3. `getFieldErrors()` - 获取所有字段的错误映射
92
+
93
+ ```javascript
94
+ try {
95
+ await validateAsync(schema, data);
96
+ } catch (error) {
97
+ const fieldErrors = error.getFieldErrors();
98
+ // { name: '字段必填', email: '邮箱格式错误' }
99
+ }
100
+ ```
101
+
102
+ #### 4. `hasFieldError(field)` - 检查字段是否有错误
103
+
104
+ ```javascript
105
+ try {
106
+ await validateAsync(schema, data);
107
+ } catch (error) {
108
+ if (error.hasFieldError('email')) {
109
+ console.log('邮箱格式错误');
110
+ }
111
+ }
112
+ ```
113
+
114
+ #### 5. `getErrorCount()` - 获取错误数量
115
+
116
+ ```javascript
117
+ try {
118
+ await validateAsync(schema, data);
119
+ } catch (error) {
120
+ console.log(`发现 ${error.getErrorCount()} 个错误`);
121
+ }
122
+ ```
123
+
124
+ ---
125
+
126
+ ## Express 集成
127
+
128
+ ### 基础集成
129
+
130
+ ```javascript
131
+ const express = require('express');
132
+ const { dsl, validateAsync, ValidationError } = require('schema-dsl');
133
+
134
+ const app = express();
135
+ app.use(express.json());
136
+
137
+ // 定义 Schema
138
+ const userSchema = dsl({
139
+ name: 'string:1-50!',
140
+ email: 'email!',
141
+ age: 'integer:18-120'
142
+ });
143
+
144
+ // 路由处理
145
+ app.post('/users', async (req, res, next) => {
146
+ try {
147
+ // 验证请求体
148
+ const validData = await validateAsync(userSchema, req.body);
149
+
150
+ // 保存到数据库
151
+ const user = await db.users.insert(validData);
152
+
153
+ res.status(201).json({ success: true, user });
154
+ } catch (error) {
155
+ next(error); // 传递给错误处理中间件
156
+ }
157
+ });
158
+
159
+ // 全局错误处理中间件
160
+ app.use((error, req, res, next) => {
161
+ if (error instanceof ValidationError) {
162
+ return res.status(error.statusCode).json(error.toJSON());
163
+ }
164
+
165
+ // 其他错误
166
+ res.status(500).json({ error: 'Internal Server Error' });
167
+ });
168
+
169
+ app.listen(3000);
170
+ ```
171
+
172
+ ### 完整 CRUD 示例
173
+
174
+ ```javascript
175
+ const { SchemaUtils } = require('schema-dsl');
176
+
177
+ // 定义完整 Schema
178
+ const fullUserSchema = dsl({
179
+ id: 'objectId!',
180
+ name: 'string:1-50!',
181
+ email: 'email!',
182
+ password: 'string:8-32!',
183
+ age: 'integer:18-120',
184
+ createdAt: 'date',
185
+ updatedAt: 'date'
186
+ });
187
+
188
+ // POST /users - 创建用户(严格模式)
189
+ const createSchema = SchemaUtils
190
+ .omit(fullUserSchema, ['id', 'createdAt', 'updatedAt'])
191
+ .strict();
192
+
193
+ app.post('/users', async (req, res, next) => {
194
+ try {
195
+ const data = await validateAsync(createSchema, req.body);
196
+ const user = await db.users.insert({
197
+ ...data,
198
+ createdAt: new Date(),
199
+ updatedAt: new Date()
200
+ });
201
+ res.status(201).json(user);
202
+ } catch (error) {
203
+ next(error);
204
+ }
205
+ });
206
+
207
+ // GET /users/:id - 查询用户(移除敏感字段)
208
+ const publicSchema = SchemaUtils
209
+ .omit(fullUserSchema, ['password'])
210
+ .clean();
211
+
212
+ app.get('/users/:id', async (req, res, next) => {
213
+ try {
214
+ const user = await db.users.findById(req.params.id);
215
+ const { validate } = require('schema-dsl');
216
+ const result = validate(publicSchema, user);
217
+ res.json(result.data); // 自动移除 password
218
+ } catch (error) {
219
+ next(error);
220
+ }
221
+ });
222
+
223
+ // PATCH /users/:id - 更新用户(部分验证)
224
+ const updateSchema = SchemaUtils
225
+ .pick(fullUserSchema, ['name', 'age'])
226
+ .partial()
227
+ .loose();
228
+
229
+ app.patch('/users/:id', async (req, res, next) => {
230
+ try {
231
+ const data = await validateAsync(updateSchema, req.body);
232
+ const user = await db.users.updateById(req.params.id, {
233
+ ...data,
234
+ updatedAt: new Date()
235
+ });
236
+ res.json(user);
237
+ } catch (error) {
238
+ next(error);
239
+ }
240
+ });
241
+
242
+ // PUT /users/:id - 替换用户(严格模式)
243
+ const replaceSchema = SchemaUtils
244
+ .omit(fullUserSchema, ['id', 'createdAt', 'updatedAt'])
245
+ .strict();
246
+
247
+ app.put('/users/:id', async (req, res, next) => {
248
+ try {
249
+ const data = await validateAsync(replaceSchema, req.body);
250
+ const user = await db.users.replaceById(req.params.id, {
251
+ ...data,
252
+ updatedAt: new Date()
253
+ });
254
+ res.json(user);
255
+ } catch (error) {
256
+ next(error);
257
+ }
258
+ });
259
+ ```
260
+
261
+ ---
262
+
263
+ ## 错误处理
264
+
265
+ ### 自定义错误格式
266
+
267
+ ```javascript
268
+ app.use((error, req, res, next) => {
269
+ if (error instanceof ValidationError) {
270
+ // 自定义错误响应格式
271
+ return res.status(422).json({
272
+ code: 'VALIDATION_FAILED',
273
+ message: '数据验证失败',
274
+ timestamp: new Date().toISOString(),
275
+ fields: error.getFieldErrors()
276
+ });
277
+ }
278
+
279
+ next(error);
280
+ });
281
+ ```
282
+
283
+ ### 分类错误处理
284
+
285
+ ```javascript
286
+ app.use((error, req, res, next) => {
287
+ if (error instanceof ValidationError) {
288
+ const fieldErrors = error.getFieldErrors();
289
+
290
+ // 邮箱格式错误
291
+ if (error.hasFieldError('email')) {
292
+ return res.status(400).json({
293
+ code: 'INVALID_EMAIL',
294
+ message: '邮箱格式错误',
295
+ field: 'email'
296
+ });
297
+ }
298
+
299
+ // 其他验证错误
300
+ return res.status(400).json(error.toJSON());
301
+ }
302
+
303
+ next(error);
304
+ });
305
+ ```
306
+
307
+ ### 日志记录
308
+
309
+ ```javascript
310
+ app.use((error, req, res, next) => {
311
+ if (error instanceof ValidationError) {
312
+ // 记录验证错误日志
313
+ logger.warn('Validation failed', {
314
+ url: req.url,
315
+ method: req.method,
316
+ errors: error.errors,
317
+ data: error.data
318
+ });
319
+
320
+ return res.status(error.statusCode).json(error.toJSON());
321
+ }
322
+
323
+ next(error);
324
+ });
325
+ ```
326
+
327
+ ---
328
+
329
+ ## 完整示例
330
+
331
+ ### 用户注册 API
332
+
333
+ ```javascript
334
+ const express = require('express');
335
+ const bcrypt = require('bcrypt');
336
+ const { dsl, validateAsync, ValidationError, SchemaUtils } = require('schema-dsl');
337
+
338
+ const app = express();
339
+ app.use(express.json());
340
+
341
+ // 基础用户 Schema
342
+ const baseUserSchema = dsl({
343
+ id: 'objectId!',
344
+ username: 'string:3-32!',
345
+ email: 'email!',
346
+ password: 'string:8-32!',
347
+ age: 'integer:18-120',
348
+ createdAt: 'date',
349
+ updatedAt: 'date'
350
+ });
351
+
352
+ // 注册 Schema(排除系统字段,严格模式)
353
+ const registerSchema = SchemaUtils
354
+ .omit(baseUserSchema, ['id', 'createdAt', 'updatedAt'])
355
+ .strict();
356
+
357
+ // 注册接口
358
+ app.post('/register', async (req, res, next) => {
359
+ try {
360
+ // 1. 验证请求数据
361
+ const data = await validateAsync(registerSchema, req.body);
362
+
363
+ // 2. 检查用户是否存在
364
+ const existingUser = await db.users.findOne({ email: data.email });
365
+ if (existingUser) {
366
+ return res.status(409).json({
367
+ code: 'USER_EXISTS',
368
+ message: '邮箱已被注册'
369
+ });
370
+ }
371
+
372
+ // 3. 加密密码
373
+ const hashedPassword = await bcrypt.hash(data.password, 10);
374
+
375
+ // 4. 保存用户
376
+ const user = await db.users.insert({
377
+ ...data,
378
+ password: hashedPassword,
379
+ createdAt: new Date(),
380
+ updatedAt: new Date()
381
+ });
382
+
383
+ // 5. 返回公开信息(移除密码)
384
+ const publicSchema = SchemaUtils
385
+ .omit(baseUserSchema, ['password'])
386
+ .clean();
387
+
388
+ const { validate } = require('schema-dsl');
389
+ const result = validate(publicSchema, user);
390
+
391
+ res.status(201).json({
392
+ success: true,
393
+ user: result.data
394
+ });
395
+
396
+ } catch (error) {
397
+ next(error);
398
+ }
399
+ });
400
+
401
+ // 全局错误处理
402
+ app.use((error, req, res, next) => {
403
+ if (error instanceof ValidationError) {
404
+ return res.status(error.statusCode).json(error.toJSON());
405
+ }
406
+
407
+ console.error('Server error:', error);
408
+ res.status(500).json({ error: 'Internal Server Error' });
409
+ });
410
+
411
+ app.listen(3000, () => {
412
+ console.log('Server running on http://localhost:3000');
413
+ });
414
+ ```
415
+
416
+ ---
417
+
418
+ ## API 参考
419
+
420
+ ### validateAsync(schema, data, options?)
421
+
422
+ **参数**:
423
+ - `schema` - JSON Schema 或 DslBuilder 实例
424
+ - `data` - 待验证的数据
425
+ - `options` - 验证选项(可选)
426
+ - `locale` - 语言设置(如 'zh-CN', 'en-US')
427
+ - `format` - 是否格式化错误(默认 true)
428
+
429
+ **返回值**:
430
+ - 验证通过:返回处理后的数据
431
+ - 验证失败:抛出 `ValidationError`
432
+
433
+ **示例**:
434
+ ```javascript
435
+ // 基础用法
436
+ const data = await validateAsync(schema, inputData);
437
+
438
+ // 指定语言
439
+ const data = await validateAsync(schema, inputData, { locale: 'zh-CN' });
440
+
441
+ // 不格式化错误
442
+ const data = await validateAsync(schema, inputData, { format: false });
443
+ ```
444
+
445
+ ### ValidationError 类
446
+
447
+ **构造函数**:
448
+ ```javascript
449
+ new ValidationError(errors, data)
450
+ ```
451
+
452
+ **属性**:
453
+ - `name: 'ValidationError'`
454
+ - `message: string` - 友好的错误消息
455
+ - `errors: Array<Object>` - 原始错误列表
456
+ - `data: any` - 原始输入数据
457
+ - `statusCode: 400` - HTTP 状态码
458
+
459
+ **方法**:
460
+ - `toJSON()` - 转换为 JSON 格式
461
+ - `getFieldError(field)` - 获取指定字段的错误
462
+ - `getFieldErrors()` - 获取所有字段的错误映射
463
+ - `hasFieldError(field)` - 检查字段是否有错误
464
+ - `getErrorCount()` - 获取错误数量
465
+
466
+ ---
467
+
468
+ ## 相关文档
469
+
470
+ - [SchemaUtils 链式调用](schema-utils-chaining.md) - Schema 复用简化方法
471
+ - [validate.md](validate.md) - 传统同步验证方法
472
+ - [error-handling.md](error-handling.md) - 错误处理指南
473
+ - [Express 示例](../examples/express-integration.js) - 完整 Express 集成示例
474
+
475
+ ---
476
+
477
+ **版本**: v2.1.0
478
+ **更新日期**: 2025-12-29
479
+ **作者**: SchemaIO Team
480
+