schema-dsl 2.3.0 → 2.3.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/.github/workflows/ci.yml +1 -3
- package/README.md +69 -7
- package/docs/FEATURE-INDEX.md +1 -1
- package/docs/INDEX.md +31 -2
- package/docs/export-guide.md +3 -0
- package/docs/export-limitations.md +551 -0
- package/docs/mongodb-exporter.md +16 -0
- package/docs/mysql-exporter.md +16 -0
- package/docs/postgresql-exporter.md +14 -0
- package/docs/schema-utils-chaining.md +146 -0
- package/docs/schema-utils.md +7 -9
- package/docs/validate-async.md +480 -0
- package/examples/array-dsl-example.js +1 -1
- package/examples/express-integration.js +376 -0
- package/examples/new-features-comparison.js +315 -0
- package/examples/schema-utils-chaining.examples.js +250 -0
- package/examples/simple-example.js +2 -2
- package/index.js +13 -1
- package/lib/adapters/DslAdapter.js +47 -1
- package/lib/core/Validator.js +60 -0
- package/lib/errors/ValidationError.js +191 -0
- package/lib/utils/SchemaUtils.js +170 -38
- package/package.json +1 -1
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
# SchemaUtils 使用指南
|
|
2
|
+
|
|
3
|
+
> Schema 复用和转换工具
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 快速开始
|
|
8
|
+
|
|
9
|
+
4 个方法复用 Schema:
|
|
10
|
+
|
|
11
|
+
```javascript
|
|
12
|
+
const { dsl, SchemaUtils } = require('schema-dsl');
|
|
13
|
+
|
|
14
|
+
const userSchema = dsl({
|
|
15
|
+
id: 'objectId!',
|
|
16
|
+
name: 'string!',
|
|
17
|
+
email: 'email!',
|
|
18
|
+
password: 'string!',
|
|
19
|
+
age: 'integer:18-120'
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
// 排除字段
|
|
23
|
+
SchemaUtils.omit(userSchema, ['password']);
|
|
24
|
+
|
|
25
|
+
// 保留字段
|
|
26
|
+
SchemaUtils.pick(userSchema, ['name', 'email']);
|
|
27
|
+
|
|
28
|
+
// 变为可选
|
|
29
|
+
SchemaUtils.partial(userSchema);
|
|
30
|
+
|
|
31
|
+
// 扩展字段
|
|
32
|
+
SchemaUtils.extend(userSchema, { avatar: 'url' });
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
---
|
|
36
|
+
|
|
37
|
+
## omit - 排除字段
|
|
38
|
+
|
|
39
|
+
```javascript
|
|
40
|
+
// 创建用户 - 排除系统字段
|
|
41
|
+
const createSchema = SchemaUtils.omit(userSchema, ['id', 'createdAt']);
|
|
42
|
+
|
|
43
|
+
// 公开信息 - 排除敏感字段
|
|
44
|
+
const publicSchema = SchemaUtils.omit(userSchema, ['password']);
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
---
|
|
48
|
+
|
|
49
|
+
## pick - 保留字段
|
|
50
|
+
|
|
51
|
+
```javascript
|
|
52
|
+
// 只允许修改部分字段
|
|
53
|
+
const updateSchema = SchemaUtils.pick(userSchema, ['name', 'age']);
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
---
|
|
57
|
+
|
|
58
|
+
## partial - 变为可选
|
|
59
|
+
|
|
60
|
+
```javascript
|
|
61
|
+
// 所有字段变为可选
|
|
62
|
+
const partialSchema = SchemaUtils.partial(userSchema);
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
---
|
|
66
|
+
|
|
67
|
+
## extend - 扩展字段
|
|
68
|
+
|
|
69
|
+
```javascript
|
|
70
|
+
// 添加新字段
|
|
71
|
+
const extendedSchema = SchemaUtils.extend(userSchema, {
|
|
72
|
+
avatar: 'url',
|
|
73
|
+
bio: 'string:0-500'
|
|
74
|
+
});
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
---
|
|
78
|
+
|
|
79
|
+
## 链式调用
|
|
80
|
+
|
|
81
|
+
```javascript
|
|
82
|
+
// pick + partial
|
|
83
|
+
SchemaUtils.pick(userSchema, ['name', 'age']).partial();
|
|
84
|
+
|
|
85
|
+
// pick + extend
|
|
86
|
+
SchemaUtils.pick(userSchema, ['name']).extend({ avatar: 'url' });
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
---
|
|
90
|
+
|
|
91
|
+
## Express 示例
|
|
92
|
+
|
|
93
|
+
```javascript
|
|
94
|
+
const { dsl, SchemaUtils, validateAsync } = require('schema-dsl');
|
|
95
|
+
|
|
96
|
+
const userSchema = dsl({
|
|
97
|
+
id: 'objectId!',
|
|
98
|
+
name: 'string!',
|
|
99
|
+
email: 'email!',
|
|
100
|
+
password: 'string!',
|
|
101
|
+
age: 'integer:18-120'
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
// POST /users - 创建
|
|
105
|
+
app.post('/users', async (req, res, next) => {
|
|
106
|
+
const schema = SchemaUtils.omit(userSchema, ['id']);
|
|
107
|
+
const data = await validateAsync(schema, req.body);
|
|
108
|
+
// 保存到数据库...
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
// GET /users/:id - 查询
|
|
112
|
+
app.get('/users/:id', async (req, res) => {
|
|
113
|
+
const schema = SchemaUtils.omit(userSchema, ['password']);
|
|
114
|
+
const user = await db.findById(req.params.id);
|
|
115
|
+
const result = validate(schema, user);
|
|
116
|
+
res.json(result.data);
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
// PATCH /users/:id - 更新
|
|
120
|
+
app.patch('/users/:id', async (req, res, next) => {
|
|
121
|
+
const schema = SchemaUtils.pick(userSchema, ['name', 'age']).partial();
|
|
122
|
+
const data = await validateAsync(schema, req.body);
|
|
123
|
+
// 更新数据库...
|
|
124
|
+
});
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
---
|
|
128
|
+
|
|
129
|
+
## API
|
|
130
|
+
|
|
131
|
+
### omit(schema, fields)
|
|
132
|
+
排除字段
|
|
133
|
+
|
|
134
|
+
### pick(schema, fields)
|
|
135
|
+
保留字段
|
|
136
|
+
|
|
137
|
+
### partial(schema, fields?)
|
|
138
|
+
变为可选
|
|
139
|
+
|
|
140
|
+
### extend(schema, extensions)
|
|
141
|
+
扩展字段
|
|
142
|
+
|
|
143
|
+
---
|
|
144
|
+
|
|
145
|
+
**版本**: v2.3.1
|
|
146
|
+
|
package/docs/schema-utils.md
CHANGED
|
@@ -130,16 +130,15 @@ const withAge = dsl({
|
|
|
130
130
|
gender: 'male|female|other'
|
|
131
131
|
});
|
|
132
132
|
|
|
133
|
-
|
|
133
|
+
// 扩展
|
|
134
|
+
const fullUser = SchemaUtils.extend(baseUser, {
|
|
135
|
+
age: 'number:18-120',
|
|
134
136
|
bio: 'string:500',
|
|
135
137
|
avatar: 'url'
|
|
136
138
|
});
|
|
137
|
-
|
|
138
|
-
// 合并
|
|
139
|
-
const fullUser = SchemaUtils.merge(baseUser, withAge, withProfile);
|
|
140
139
|
```
|
|
141
140
|
|
|
142
|
-
**说明**:
|
|
141
|
+
**说明**: 扩展字段,合并 properties 和 required 数组
|
|
143
142
|
|
|
144
143
|
---
|
|
145
144
|
|
|
@@ -428,10 +427,9 @@ const profileSchema = dsl({
|
|
|
428
427
|
});
|
|
429
428
|
|
|
430
429
|
// 完整用户
|
|
431
|
-
const userSchema = SchemaUtils.
|
|
432
|
-
registerSchema,
|
|
433
|
-
|
|
434
|
-
dsl(fields.address())
|
|
430
|
+
const userSchema = SchemaUtils.extend(
|
|
431
|
+
SchemaUtils.extend(registerSchema, profileSchema),
|
|
432
|
+
fields.address()
|
|
435
433
|
);
|
|
436
434
|
```
|
|
437
435
|
|
|
@@ -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
|
+
|
|
@@ -102,7 +102,7 @@ const withAge = dsl({
|
|
|
102
102
|
});
|
|
103
103
|
|
|
104
104
|
// ✨ 新特性:merge方法
|
|
105
|
-
const
|
|
105
|
+
const extendedSchema = SchemaUtils.extend(baseUser, withAge);
|
|
106
106
|
|
|
107
107
|
console.log('合并后字段数:', Object.keys(mergedSchema.properties).length);
|
|
108
108
|
console.log('');
|