schema-dsl 1.2.5 → 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.
Files changed (243) hide show
  1. package/CHANGELOG.md +130 -238
  2. package/LICENSE +21 -21
  3. package/README.md +628 -2486
  4. package/dist/DslBuilder-BIgQOAXp.d.ts +343 -0
  5. package/dist/DslBuilder-CjHTucNQ.d.cts +343 -0
  6. package/dist/Validator-CllRdrY0.d.ts +192 -0
  7. package/dist/Validator-D6okG9tr.d.cts +192 -0
  8. package/dist/index.cjs +6640 -0
  9. package/dist/index.d.cts +1151 -0
  10. package/dist/index.d.ts +1151 -0
  11. package/dist/index.js +6574 -0
  12. package/dist/plugin-CIKtTMtS.d.cts +246 -0
  13. package/dist/plugin-CIKtTMtS.d.ts +246 -0
  14. package/dist/plugins/custom-format.cjs +3818 -0
  15. package/dist/plugins/custom-format.d.cts +12 -0
  16. package/dist/plugins/custom-format.d.ts +12 -0
  17. package/dist/plugins/custom-format.js +3788 -0
  18. package/dist/plugins/custom-type-example.cjs +3811 -0
  19. package/dist/plugins/custom-type-example.d.cts +8 -0
  20. package/dist/plugins/custom-type-example.d.ts +8 -0
  21. package/dist/plugins/custom-type-example.js +3781 -0
  22. package/dist/plugins/custom-validator.cjs +144 -0
  23. package/dist/plugins/custom-validator.d.cts +10 -0
  24. package/dist/plugins/custom-validator.d.ts +10 -0
  25. package/dist/plugins/custom-validator.js +119 -0
  26. package/docs/FEATURE-INDEX.md +553 -519
  27. package/docs/add-custom-locale.md +496 -483
  28. package/docs/add-keyword.md +24 -0
  29. package/docs/api-reference.md +1047 -805
  30. package/docs/api.md +13 -0
  31. package/docs/best-practices-project-structure.md +417 -408
  32. package/docs/best-practices.md +712 -672
  33. package/docs/cache-manager.md +344 -336
  34. package/docs/compile.md +45 -0
  35. package/docs/conditional-api.md +1307 -1278
  36. package/docs/custom-extensions-guide.md +339 -411
  37. package/docs/design-philosophy.md +606 -601
  38. package/docs/doc-index.md +324 -0
  39. package/docs/dsl-syntax.md +714 -664
  40. package/docs/dynamic-locale.md +608 -598
  41. package/docs/enum.md +482 -475
  42. package/docs/error-handling.md +1975 -1966
  43. package/docs/export-guide.md +501 -462
  44. package/docs/export-limitations.md +567 -551
  45. package/docs/faq.md +596 -577
  46. package/docs/frontend-i18n-guide.md +307 -293
  47. package/docs/i18n-user-guide.md +487 -474
  48. package/docs/i18n.md +476 -457
  49. package/docs/index.md +48 -0
  50. package/docs/json-schema-basics.md +40 -0
  51. package/docs/label-vs-description.md +271 -262
  52. package/docs/markdown-exporter.md +406 -397
  53. package/docs/mongodb-exporter.md +302 -295
  54. package/docs/multi-language.md +26 -0
  55. package/docs/multi-type-support.md +322 -329
  56. package/docs/mysql-exporter.md +280 -273
  57. package/docs/number-operators.md +449 -442
  58. package/docs/optional-marker-guide.md +326 -321
  59. package/docs/performance-guide.md +49 -0
  60. package/docs/plugin-system.md +381 -542
  61. package/docs/plugin-type-registration.md +34 -0
  62. package/docs/postgresql-exporter.md +311 -304
  63. package/docs/public/favicon.svg +5 -0
  64. package/docs/quick-start.md +435 -761
  65. package/docs/runtime-locale-support.md +532 -521
  66. package/docs/schema-helper.md +345 -340
  67. package/docs/schema-utils-advanced-issues.md +23 -0
  68. package/docs/schema-utils-best-practices.md +20 -0
  69. package/docs/schema-utils-chaining.md +150 -143
  70. package/docs/schema-utils.md +524 -490
  71. package/docs/security-checklist.md +20 -0
  72. package/docs/string-extensions.md +488 -480
  73. package/docs/troubleshooting.md +486 -471
  74. package/docs/type-converter.md +310 -319
  75. package/docs/type-reference.md +242 -219
  76. package/docs/typescript-guide.md +584 -573
  77. package/docs/union-type-guide.md +157 -147
  78. package/docs/union-types.md +284 -277
  79. package/docs/validate-async.md +491 -480
  80. package/docs/validate-batch.md +49 -0
  81. package/docs/validate-dsl-object-support.md +578 -573
  82. package/docs/validate.md +506 -486
  83. package/docs/validation-guide.md +502 -484
  84. package/docs/validator.md +39 -0
  85. package/package.json +131 -73
  86. package/plugins/custom-format.cjs +8 -0
  87. package/plugins/custom-type-example.cjs +8 -0
  88. package/plugins/custom-validator.cjs +8 -0
  89. package/src/adapters/DslAdapter.ts +111 -0
  90. package/src/adapters/index.ts +1 -0
  91. package/src/config/constants.ts +83 -0
  92. package/src/config/index.ts +2 -0
  93. package/src/config/patterns.ts +77 -0
  94. package/src/core/CacheManager.ts +169 -0
  95. package/src/core/ConditionalBuilder.ts +382 -0
  96. package/src/core/ConditionalRuntime.ts +28 -0
  97. package/src/core/ConditionalValidator.ts +255 -0
  98. package/src/core/DslBuilder.ts +687 -0
  99. package/src/core/ErrorCodes.ts +38 -0
  100. package/src/core/ErrorFormatter.ts +271 -0
  101. package/src/core/JSONSchemaCore.ts +65 -0
  102. package/src/core/Locale.ts +187 -0
  103. package/src/core/MessageTemplate.ts +42 -0
  104. package/src/core/ObjectDslBuilder.ts +64 -0
  105. package/src/core/PluginManager.ts +326 -0
  106. package/src/core/StringExtensions.ts +140 -0
  107. package/src/core/TemplateEngine.ts +44 -0
  108. package/src/core/Validator.ts +448 -0
  109. package/src/errors/I18nError.ts +159 -0
  110. package/src/errors/ValidationError.ts +105 -0
  111. package/src/exporters/BaseExporter.ts +60 -0
  112. package/src/exporters/MarkdownExporter.ts +305 -0
  113. package/src/exporters/MongoDBExporter.ts +126 -0
  114. package/src/exporters/MySQLExporter.ts +156 -0
  115. package/src/exporters/PostgreSQLExporter.ts +222 -0
  116. package/src/exporters/index.ts +18 -0
  117. package/src/index.ts +651 -0
  118. package/{lib/locales/en-US.js → src/locales/en-US.ts} +160 -176
  119. package/{lib/locales/es-ES.js → src/locales/es-ES.ts} +160 -113
  120. package/{lib/locales/fr-FR.js → src/locales/fr-FR.ts} +160 -113
  121. package/src/locales/index.ts +103 -0
  122. package/{lib/locales/ja-JP.js → src/locales/ja-JP.ts} +160 -118
  123. package/src/locales/types.ts +156 -0
  124. package/{lib/locales/zh-CN.js → src/locales/zh-CN.ts} +160 -177
  125. package/src/parser/ConstraintParser.ts +101 -0
  126. package/src/parser/DslParser.ts +470 -0
  127. package/src/parser/SchemaCompiler.ts +66 -0
  128. package/src/parser/TypeRegistry.ts +250 -0
  129. package/src/parser/index.ts +6 -0
  130. package/src/plugins/custom-format.ts +124 -0
  131. package/src/plugins/custom-type-example.ts +106 -0
  132. package/src/plugins/custom-validator.ts +138 -0
  133. package/src/types/conditional.ts +28 -0
  134. package/src/types/config.ts +59 -0
  135. package/src/types/dsl.ts +131 -0
  136. package/src/types/error.ts +60 -0
  137. package/src/types/index.ts +17 -0
  138. package/src/types/infer.ts +128 -0
  139. package/src/types/plugin.ts +58 -0
  140. package/src/types/safe-regex.d.ts +9 -0
  141. package/src/types/schema.ts +66 -0
  142. package/src/types/validate.ts +71 -0
  143. package/src/utils/SchemaHelper.ts +196 -0
  144. package/src/utils/SchemaUtils.ts +365 -0
  145. package/src/utils/TypeConverter.ts +215 -0
  146. package/src/utils/index.ts +10 -0
  147. package/src/validators/CustomKeywords.ts +477 -0
  148. package/.eslintignore +0 -11
  149. package/.eslintrc.json +0 -27
  150. package/CONTRIBUTING.md +0 -368
  151. package/STATUS.md +0 -491
  152. package/changelogs/v1.0.0.md +0 -328
  153. package/changelogs/v1.0.9.md +0 -367
  154. package/changelogs/v1.1.0.md +0 -389
  155. package/changelogs/v1.1.1.md +0 -308
  156. package/changelogs/v1.1.2.md +0 -183
  157. package/changelogs/v1.1.3.md +0 -161
  158. package/changelogs/v1.1.4.md +0 -432
  159. package/changelogs/v1.1.5.md +0 -493
  160. package/changelogs/v1.1.6.md +0 -211
  161. package/changelogs/v1.1.8.md +0 -376
  162. package/changelogs/v1.2.3.md +0 -124
  163. package/docs/INDEX.md +0 -252
  164. package/docs/issues-resolved-summary.md +0 -196
  165. package/docs/performance-benchmark-report.md +0 -179
  166. package/docs/performance-quick-reference.md +0 -123
  167. package/docs/user-questions-answered.md +0 -353
  168. package/docs/validation-rules-v1.0.2.md +0 -1608
  169. package/examples/README.md +0 -81
  170. package/examples/array-dsl-example.js +0 -227
  171. package/examples/conditional-example.js +0 -288
  172. package/examples/conditional-non-object.js +0 -129
  173. package/examples/conditional-validate-example.js +0 -321
  174. package/examples/custom-extension.js +0 -85
  175. package/examples/dsl-match-example.js +0 -74
  176. package/examples/dsl-style.js +0 -118
  177. package/examples/dynamic-locale-configuration.js +0 -348
  178. package/examples/dynamic-locale-example.js +0 -287
  179. package/examples/enum.examples.js +0 -324
  180. package/examples/export-demo.js +0 -130
  181. package/examples/express-integration.js +0 -376
  182. package/examples/i18n-error-handling-complete.js +0 -381
  183. package/examples/i18n-error-handling-quickstart.md +0 -0
  184. package/examples/i18n-error.examples.js +0 -181
  185. package/examples/i18n-full-demo.js +0 -301
  186. package/examples/i18n-memory-safety.examples.js +0 -268
  187. package/examples/markdown-export.js +0 -71
  188. package/examples/middleware-usage.js +0 -93
  189. package/examples/new-features-comparison.js +0 -315
  190. package/examples/password-reset/README.md +0 -153
  191. package/examples/password-reset/schema.js +0 -26
  192. package/examples/password-reset/test.js +0 -101
  193. package/examples/plugin-system.examples.js +0 -205
  194. package/examples/schema-utils-chaining.examples.js +0 -250
  195. package/examples/simple-example.js +0 -122
  196. package/examples/slug.examples.js +0 -179
  197. package/examples/string-extensions.js +0 -297
  198. package/examples/union-type-example.js +0 -127
  199. package/examples/union-types-example.js +0 -77
  200. package/examples/user-registration/README.md +0 -156
  201. package/examples/user-registration/routes.js +0 -92
  202. package/examples/user-registration/schema.js +0 -150
  203. package/examples/user-registration/server.js +0 -74
  204. package/index.d.ts +0 -3658
  205. package/index.js +0 -475
  206. package/index.mjs +0 -60
  207. package/lib/adapters/DslAdapter.js +0 -995
  208. package/lib/adapters/index.js +0 -20
  209. package/lib/config/constants.js +0 -286
  210. package/lib/config/patterns/common.js +0 -47
  211. package/lib/config/patterns/creditCard.js +0 -9
  212. package/lib/config/patterns/idCard.js +0 -9
  213. package/lib/config/patterns/index.js +0 -9
  214. package/lib/config/patterns/licensePlate.js +0 -4
  215. package/lib/config/patterns/passport.js +0 -4
  216. package/lib/config/patterns/phone.js +0 -9
  217. package/lib/config/patterns/postalCode.js +0 -5
  218. package/lib/core/CacheManager.js +0 -376
  219. package/lib/core/ConditionalBuilder.js +0 -503
  220. package/lib/core/DslBuilder.js +0 -1589
  221. package/lib/core/ErrorCodes.js +0 -233
  222. package/lib/core/ErrorFormatter.js +0 -445
  223. package/lib/core/JSONSchemaCore.js +0 -347
  224. package/lib/core/Locale.js +0 -130
  225. package/lib/core/MessageTemplate.js +0 -98
  226. package/lib/core/PluginManager.js +0 -448
  227. package/lib/core/StringExtensions.js +0 -240
  228. package/lib/core/Validator.js +0 -654
  229. package/lib/errors/I18nError.js +0 -328
  230. package/lib/errors/ValidationError.js +0 -191
  231. package/lib/exporters/MarkdownExporter.js +0 -420
  232. package/lib/exporters/MongoDBExporter.js +0 -162
  233. package/lib/exporters/MySQLExporter.js +0 -212
  234. package/lib/exporters/PostgreSQLExporter.js +0 -289
  235. package/lib/exporters/index.js +0 -24
  236. package/lib/locales/index.js +0 -8
  237. package/lib/utils/LRUCache.js +0 -174
  238. package/lib/utils/SchemaHelper.js +0 -240
  239. package/lib/utils/SchemaUtils.js +0 -445
  240. package/lib/utils/TypeConverter.js +0 -245
  241. package/lib/utils/index.js +0 -13
  242. package/lib/validators/CustomKeywords.js +0 -616
  243. package/lib/validators/index.js +0 -11
@@ -1,205 +0,0 @@
1
- /**
2
- * 插件系统使用示例
3
- */
4
-
5
- const { dsl, validate, PluginManager } = require('../index');
6
-
7
- // ========== 1. 基础使用 ==========
8
-
9
- console.log('=== 1. 基础使用 ===\n');
10
-
11
- // 创建插件管理器
12
- const pluginManager = new PluginManager();
13
-
14
- // 注册插件
15
- const customValidatorPlugin = require('../plugins/custom-validator');
16
- pluginManager.register(customValidatorPlugin);
17
-
18
- const customFormatPlugin = require('../plugins/custom-format');
19
- pluginManager.register(customFormatPlugin);
20
-
21
- // 安装插件
22
- const schemaDsl = require('../index');
23
- pluginManager.install(schemaDsl);
24
-
25
- console.log('已安装插件:', pluginManager.list());
26
- console.log('');
27
-
28
- // ========== 2. 使用自定义格式 ==========
29
-
30
- console.log('=== 2. 使用自定义格式 ===\n');
31
-
32
- const contactSchema = dsl({
33
- phone: 'string!',
34
- email: 'email!',
35
- wechat: 'string'
36
- });
37
-
38
- // 测试数据
39
- const validContact = {
40
- phone: '13800138000',
41
- email: 'test@example.com',
42
- wechat: 'my_wechat_id'
43
- };
44
-
45
- const result1 = validate(contactSchema, validContact);
46
- console.log('验证结果:', result1.valid ? '✅ 通过' : '❌ 失败');
47
- if (!result1.valid) {
48
- console.log('错误:', result1.errors);
49
- }
50
- console.log('');
51
-
52
- // ========== 3. 使用钩子系统 ==========
53
-
54
- console.log('=== 3. 使用钩子系统 ===\n');
55
-
56
- // 注册钩子
57
- pluginManager.hook('onBeforeValidate', (schema, data) => {
58
- console.log('[Hook] 验证前:', { schema: '...', data });
59
- });
60
-
61
- pluginManager.hook('onAfterValidate', (result) => {
62
- console.log('[Hook] 验证后:', { valid: result.valid });
63
- });
64
-
65
- // 运行钩子
66
- const testSchema = dsl({ name: 'string!' });
67
- const testData = { name: 'John' };
68
-
69
- pluginManager.runHook('onBeforeValidate', testSchema, testData);
70
- const result2 = validate(testSchema, testData);
71
- pluginManager.runHook('onAfterValidate', result2);
72
- console.log('');
73
-
74
- // ========== 4. 自定义插件 ==========
75
-
76
- console.log('=== 4. 自定义插件 ===\n');
77
-
78
- // 创建自定义插件
79
- const myPlugin = {
80
- name: 'my-plugin',
81
- version: '1.0.0',
82
- description: '我的自定义插件',
83
-
84
- install(schemaDsl, options, context) {
85
- console.log('[Plugin] my-plugin 安装中...');
86
- console.log(' 选项:', options);
87
- console.log(' 已注册插件数:', context.plugins.size);
88
-
89
- // 添加自定义方法
90
- schemaDsl.myCustomMethod = () => {
91
- console.log(' 这是自定义方法!');
92
- };
93
- },
94
-
95
- uninstall(schemaDsl, context) {
96
- console.log('[Plugin] my-plugin 卸载中...');
97
- delete schemaDsl.myCustomMethod;
98
- },
99
-
100
- hooks: {
101
- onBeforeValidate(schema, data) {
102
- console.log(' [my-plugin] 验证前钩子');
103
- }
104
- }
105
- };
106
-
107
- // 注册并安装
108
- pluginManager.register(myPlugin);
109
- pluginManager.install(schemaDsl, 'my-plugin', { custom: true });
110
-
111
- // 使用自定义方法
112
- if (schemaDsl.myCustomMethod) {
113
- schemaDsl.myCustomMethod();
114
- }
115
- console.log('');
116
-
117
- // ========== 5. 插件管理 ==========
118
-
119
- console.log('=== 5. 插件管理 ===\n');
120
-
121
- // 查看所有插件
122
- console.log('所有插件:', pluginManager.list());
123
-
124
- // 检查插件是否存在
125
- console.log('my-plugin 是否存在:', pluginManager.has('my-plugin'));
126
-
127
- // 获取插件数量
128
- console.log('插件数量:', pluginManager.size);
129
- console.log('');
130
-
131
- // ========== 6. 实用插件示例 ==========
132
-
133
- console.log('=== 6. 实用插件示例 ===\n');
134
-
135
- // 日志插件
136
- const loggingPlugin = {
137
- name: 'logging',
138
- version: '1.0.0',
139
-
140
- install(schemaDsl, options, context) {
141
- // 包装 validate 方法
142
- const originalValidate = schemaDsl.validate;
143
- schemaDsl.validate = function (...args) {
144
- console.log('[Logging] 开始验证');
145
- const start = Date.now();
146
- const result = originalValidate.apply(this, args);
147
- const duration = Date.now() - start;
148
- console.log(`[Logging] 验证完成,耗时 ${duration}ms,结果: ${result.valid ? '通过' : '失败'}`);
149
- return result;
150
- };
151
- }
152
- };
153
-
154
- pluginManager.register(loggingPlugin);
155
- pluginManager.install(schemaDsl, 'logging');
156
-
157
- // 测试日志插件
158
- const schema = dsl({ email: 'email!' });
159
- validate(schema, { email: 'test@example.com' });
160
- console.log('');
161
-
162
- // ========== 7. 卸载插件 ==========
163
-
164
- console.log('=== 7. 卸载插件 ===\n');
165
-
166
- pluginManager.uninstall('my-plugin', schemaDsl);
167
- console.log('my-plugin 已卸载');
168
- console.log('当前插件数:', pluginManager.size);
169
- console.log('');
170
-
171
- // ========== 8. 批量插件 ==========
172
-
173
- console.log('=== 8. 批量插件 ===\n');
174
-
175
- // 清空所有插件
176
- pluginManager.clear(schemaDsl);
177
- console.log('所有插件已清空');
178
- console.log('当前插件数:', pluginManager.size);
179
- console.log('');
180
-
181
- // 批量注册多个插件
182
- const plugins = [
183
- customValidatorPlugin,
184
- customFormatPlugin
185
- ];
186
-
187
- plugins.forEach(plugin => pluginManager.register(plugin));
188
- pluginManager.install(schemaDsl); // 安装所有插件
189
-
190
- console.log('批量安装完成:', pluginManager.list());
191
- console.log('');
192
-
193
- // ========== 总结 ==========
194
-
195
- console.log('=== 总结 ===\n');
196
- console.log('✅ 插件系统支持:');
197
- console.log(' - 动态注册/卸载插件');
198
- console.log(' - 生命周期钩子');
199
- console.log(' - 自定义验证器和格式');
200
- console.log(' - 插件间通信');
201
- console.log(' - 事件监听');
202
- console.log('');
203
- console.log('示例运行完成!');
204
-
205
-
@@ -1,250 +0,0 @@
1
- /**
2
- * SchemaUtils 核心方法示例
3
- *
4
- * 展示 v1.0.3 简化后的核心 4 个方法:
5
- * 1. omit() - 排除字段
6
- * 2. pick() - 保留字段
7
- * 3. partial() - 部分验证
8
- * 4. extend() - 扩展字段
9
- *
10
- * @version 1.0.3 (简化版)
11
- * @date 2025-12-29
12
- */
13
-
14
- const { dsl, validate, SchemaUtils } = require('../index');
15
-
16
- console.log('========================================');
17
- console.log(' SchemaUtils 核心方法示例');
18
- console.log('========================================\n');
19
-
20
- // ===== 定义基础 Schema =====
21
-
22
- const fullUserSchema = dsl({
23
- id: 'objectId!',
24
- name: 'string:1-50!',
25
- email: 'email!',
26
- password: 'string:8-32!',
27
- age: 'integer:18-120',
28
- role: 'admin|user|guest',
29
- createdAt: 'date',
30
- updatedAt: 'date'
31
- });
32
-
33
- console.log('基础 Schema 字段:', Object.keys(fullUserSchema.properties));
34
- console.log('必填字段:', fullUserSchema.required);
35
- console.log('');
36
-
37
- // ===== 1. omit() - 排除字段 =====
38
-
39
- console.log('========== 1. omit() - 排除字段 ==========\n');
40
-
41
- const publicSchema = SchemaUtils.omit(fullUserSchema, ['password', 'createdAt', 'updatedAt']);
42
-
43
- console.log('原 Schema 字段:', Object.keys(fullUserSchema.properties));
44
- console.log('omit 后字段:', Object.keys(publicSchema.properties));
45
- console.log('password 字段被移除:', publicSchema.properties.password === undefined);
46
- console.log('');
47
-
48
- // ===== 2. pick() - 保留字段 =====
49
-
50
- console.log('========== 2. pick() - 保留字段 ==========\n');
51
-
52
- const nameEmailSchema = SchemaUtils.pick(fullUserSchema, ['name', 'email']);
53
-
54
- console.log('原 Schema 字段:', Object.keys(fullUserSchema.properties));
55
- console.log('pick 后字段:', Object.keys(nameEmailSchema.properties));
56
- console.log('只保留 name 和 email');
57
- console.log('');
58
-
59
- // ===== 3. partial() - 部分验证 =====
60
-
61
- console.log('========== 3. partial() - 部分验证 ==========\n');
62
-
63
- const partialSchema = SchemaUtils.partial(fullUserSchema);
64
-
65
- console.log('原 Schema 必填字段:', fullUserSchema.required);
66
- console.log('partial Schema 必填字段:', partialSchema.required);
67
-
68
- // 测试:缺少必填字段
69
- const result4 = validate(partialSchema, {
70
- name: 'John'
71
- // 缺少其他必填字段
72
- });
73
-
74
- console.log('\n验证结果(缺少必填字段):');
75
- console.log(' valid:', result4.valid);
76
- if (result4.valid) {
77
- console.log(' 数据:', result4.data);
78
- }
79
- console.log('');
80
-
81
- // 部分验证 - 只验证指定字段
82
- const nameAgeSchema = SchemaUtils.partial(fullUserSchema, ['name', 'age']);
83
-
84
- console.log('partial(schema, [name, age]) 保留字段:', Object.keys(nameAgeSchema.properties));
85
-
86
- const result5 = validate(nameAgeSchema, {
87
- name: 'John',
88
- age: 30
89
- });
90
-
91
- console.log('验证结果(只验证 name 和 age):');
92
- console.log(' valid:', result5.valid);
93
- console.log('');
94
-
95
- // ===== 4. extend() - 扩展字段 =====
96
-
97
- console.log('========== 4. extend() - 扩展字段 ==========\n');
98
-
99
- const extendedSchema = SchemaUtils.extend(fullUserSchema, {
100
- avatar: 'url',
101
- bio: 'string:0-500'
102
- });
103
-
104
- console.log('原 Schema 字段:', Object.keys(fullUserSchema.properties));
105
- console.log('extend 后字段:', Object.keys(extendedSchema.properties));
106
- console.log('新增字段: avatar, bio');
107
- console.log('');
108
-
109
- // ===== 5. 链式调用 =====
110
-
111
- console.log('========== 5. 链式调用 ==========\n');
112
-
113
- // 示例 1: omit
114
- console.log('示例 1: omit (创建用户 Schema)');
115
- const createSchema = SchemaUtils.omit(fullUserSchema, ['id', 'createdAt', 'updatedAt']);
116
-
117
- console.log(' 字段:', Object.keys(createSchema.properties));
118
- console.log('');
119
-
120
- // 示例 2: pick + partial
121
- console.log('示例 2: pick + partial (更新用户 Schema)');
122
- const updateSchema = SchemaUtils
123
- .pick(fullUserSchema, ['name', 'age'])
124
- .partial();
125
-
126
- console.log(' 字段:', Object.keys(updateSchema.properties));
127
- console.log(' 必填字段:', updateSchema.required);
128
- console.log('');
129
-
130
- // 示例 3: pick + extend (用户建议的常见场景)
131
- console.log('示例 3: pick + extend (自定义用户 Schema)');
132
- const customSchema = SchemaUtils
133
- .pick(fullUserSchema, ['name', 'email'])
134
- .extend({ avatar: 'url', bio: 'string:0-500' });
135
-
136
- console.log(' 字段:', Object.keys(customSchema.properties));
137
- console.log('');
138
-
139
- // 示例 4: omit + extend
140
- console.log('示例 4: omit + extend (增强用户 Schema)');
141
- const enhancedSchema = SchemaUtils
142
- .omit(fullUserSchema, ['password'])
143
- .extend({ avatar: 'url', bio: 'string:0-500' });
144
-
145
- console.log(' 字段:', Object.keys(enhancedSchema.properties));
146
- console.log(' 新增字段: avatar, bio');
147
- console.log('');
148
-
149
- // ===== 6. 实际 CRUD 场景 =====
150
-
151
- console.log('========== 6. 实际 CRUD 场景 ==========\n');
152
-
153
- console.log('场景 1: POST /users - 创建用户');
154
- const postSchema = SchemaUtils.omit(fullUserSchema, ['id', 'createdAt', 'updatedAt']);
155
-
156
- const postData = {
157
- name: 'John Doe',
158
- email: 'john@example.com',
159
- password: 'password123',
160
- age: 30,
161
- role: 'user'
162
- };
163
-
164
- const postResult = validate(postSchema, postData);
165
- console.log(' 验证结果:', postResult.valid);
166
- console.log(' 数据:', postResult.data);
167
- console.log('');
168
-
169
- console.log('场景 2: GET /users/:id - 查询用户');
170
- const getSchema = SchemaUtils.omit(fullUserSchema, ['password']);
171
-
172
- const userData = {
173
- id: '507f1f77bcf86cd799439011',
174
- name: 'John Doe',
175
- email: 'john@example.com',
176
- password: 'password123', // 已从 schema 移除,但验证时会被忽略
177
- age: 30,
178
- role: 'user',
179
- createdAt: new Date(),
180
- updatedAt: new Date()
181
- };
182
-
183
- const getResult = validate(getSchema, userData);
184
- console.log(' 验证结果:', getResult.valid);
185
- console.log(' 保留字段:', Object.keys(getResult.data));
186
- console.log('');
187
-
188
- console.log('场景 3: PATCH /users/:id - 部分更新用户');
189
- const patchSchema = SchemaUtils
190
- .pick(fullUserSchema, ['name', 'age'])
191
- .partial();
192
-
193
- const patchData = {
194
- name: 'John Updated'
195
- // 只更新 name,age 缺失也可以
196
- };
197
-
198
- const patchResult = validate(patchSchema, patchData);
199
- console.log(' 验证结果:', patchResult.valid);
200
- console.log(' 数据:', patchResult.data);
201
- console.log('');
202
-
203
- console.log('场景 4: PUT /users/:id - 替换用户');
204
- const putSchema = SchemaUtils.omit(fullUserSchema, ['id', 'createdAt', 'updatedAt']);
205
-
206
- const putData = {
207
- name: 'John Replaced',
208
- email: 'john.new@example.com',
209
- password: 'newpassword123',
210
- age: 31,
211
- role: 'admin'
212
- };
213
-
214
- const putResult = validate(putSchema, putData);
215
- console.log(' 验证结果:', putResult.valid);
216
- console.log(' 数据:', putResult.data);
217
- console.log('');
218
-
219
- // ===== 7. 不可变性验证 =====
220
-
221
- console.log('========== 7. 不可变性验证 ==========\n');
222
-
223
- const original = dsl({
224
- name: 'string!',
225
- email: 'email!'
226
- });
227
-
228
- const modified = SchemaUtils.omit(original, ['email']);
229
-
230
- console.log('原 Schema 字段:', Object.keys(original.properties));
231
- console.log('修改后 Schema 字段:', Object.keys(modified.properties));
232
- console.log('原 Schema 未被修改:', original.properties.email !== undefined);
233
- console.log('');
234
-
235
- console.log('========================================');
236
- console.log(' 所有示例运行完成!');
237
- console.log('========================================\n');
238
-
239
- console.log('核心方法总结:');
240
- console.log(' 1. omit() - 排除字段(50%场景)');
241
- console.log(' 2. pick() - 保留字段(30%场景)');
242
- console.log(' 3. partial() - 部分验证(25%场景)');
243
- console.log(' 4. extend() - 扩展字段(15%场景)');
244
- console.log('');
245
- console.log('常见组合:');
246
- console.log(' - POST: omit(系统字段)');
247
- console.log(' - GET: omit(敏感字段)');
248
- console.log(' - PATCH: pick(可修改字段).partial()');
249
- console.log(' - 自定义: pick(基础字段).extend(新字段)');
250
-
@@ -1,122 +0,0 @@
1
- /**
2
- * SchemaIO v2.0.1 - 简洁示例
3
- *
4
- * 展示最简洁、最直观的用法
5
- */
6
-
7
- const { dsl, validate, SchemaUtils } = require('../index');
8
-
9
- console.log('========== SchemaIO v2.0.1 简洁示例 ==========\n');
10
-
11
- // ========== 1. 数组验证 - 超简洁 ==========
12
- console.log('✨ 1. 数组验证');
13
-
14
- const articleSchema = dsl({
15
- title: 'string:5-100!',
16
- tags: 'array!1-10' // ✨ 简洁:必填,1-10个元素
17
- });
18
-
19
- console.log('验证文章:', validate(articleSchema, {
20
- title: 'Hello World',
21
- tags: ['javascript', 'nodejs']
22
- }).valid);
23
- console.log('');
24
-
25
- // ========== 2. when条件 - 超直观 ==========
26
- console.log('✨ 2. 条件验证');
27
-
28
- const contactSchema = dsl({
29
- type: 'email|phone',
30
- contact: dsl.match('type', {
31
- email: 'email!',
32
- phone: 'phone:cn!'
33
- })
34
- });
35
-
36
- console.log('验证邮箱:', validate(contactSchema, { type: 'email', contact: 'test@example.com' }).valid);
37
- console.log('验证手机:', validate(contactSchema, { type: 'phone', contact: '13800138000' }).valid);
38
- console.log('');
39
-
40
- // ========== 3. 快捷方法 - 不用找正则 ==========
41
- console.log('✨ 3. 快捷方法');
42
-
43
- const userSchema = dsl({
44
- mobile: 'string!'.phoneNumber('cn'),
45
- id: 'string!'.idCard('cn')
46
- });
47
-
48
- console.log('验证快捷方法:', validate(userSchema, {
49
- mobile: '13800138000',
50
- id: '110101199003071234'
51
- }).valid);
52
- console.log('');
53
-
54
- // ========== 4. Schema复用 - 不重复代码 ==========
55
- console.log('✨ 4. Schema复用');
56
-
57
- // 定义一次,到处使用
58
- const emailField = SchemaUtils.reusable(() => dsl('email!'));
59
-
60
- const loginForm = dsl({ email: emailField() });
61
- const registerForm = dsl({ email: emailField(), name: 'string!' });
62
-
63
- console.log('复用Schema成功');
64
- console.log('');
65
-
66
- // ========== 5. Schema合并 - 灵活组合 ==========
67
- console.log('✨ 5. Schema合并');
68
-
69
- const baseUser = dsl({ name: 'string!', email: 'email!' });
70
- const withAge = dsl({ age: 'number:18-120' });
71
-
72
- const fullUser = SchemaUtils.extend(baseUser, withAge);
73
-
74
- console.log('合并后字段:', Object.keys(fullUser.properties));
75
- console.log('');
76
-
77
- // ========== 6. 批量验证 - 快50倍 ==========
78
- console.log('✨ 6. 批量验证');
79
-
80
- const users = [
81
- { email: 'user1@example.com' },
82
- { email: 'invalid' },
83
- { email: 'user3@example.com' }
84
- ];
85
-
86
- const { Validator } = require('../index');
87
- const batchResult = SchemaUtils.validateBatch(
88
- dsl({ email: 'email!' }),
89
- users,
90
- new Validator() // 批量验证需要 Validator 实例以复用编译结果
91
- );
92
-
93
- console.log('批量验证:', {
94
- 总数: batchResult.summary.total,
95
- 有效: batchResult.summary.valid,
96
- 无效: batchResult.summary.invalid,
97
- 耗时: `${batchResult.summary.duration}ms`
98
- });
99
- console.log('');
100
-
101
- // ========== 总结 ==========
102
- console.log('========== 核心理念 ==========');
103
- console.log(`
104
- ✨ SchemaIO v2.0.1 三大特点:
105
-
106
- 1. 简洁
107
- 'array!1-10' // 一眼看懂
108
- .phoneNumber('cn') // 不用找正则
109
-
110
- 2. 直观
111
- dsl.match('type', { // 清晰的条件映射
112
- email: 'email!',
113
- phone: 'string:11!'
114
- })
115
-
116
- 3. 强大
117
- SchemaUtils.extend() // 扩展字段
118
- validateBatch() // 快50倍
119
-
120
- 🎉 简洁 + 直观 + 强大 = 完美验证库!
121
- `);
122
-