node 响应结果封装
创建 /models/Result.js
文件:
const {
CODE_ERROR,
CODE_SUCCESS
} = require('../utils/constant')
class Result {
constructor(data, msg = '操作成功', options) {
this.data = null
if (arguments.length === 0) {
this.msg = '操作成功'
} else if (arguments.length === 1) {
this.msg = data
} else {
this.data = data
this.msg = msg
if (options) {
this.options = options
}
}
}
createResult() {
if (!this.code) {
this.code = CODE_SUCCESS
}
let base = {
code: this.code,
msg: this.msg
}
if (this.data) {
base.data = this.data
}
if (this.options) {
base = { ...base, ...this.options }
}
console.log(base)
return base
}
json(res) {
res.json(this.createResult())
}
success(res) {
this.code = CODE_SUCCESS
this.json(res)
}
fail(res) {
this.code = CODE_ERROR
this.json(res)
}
}
module.exports = Result
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
我们还需要创建 /utils/constant.js
:
module.exports = {
CODE_ERROR: -1,
CODE_SUCCESS: 0
}
1
2
3
4
2
3
4
Result 使用了 ES6 的 Class,使用方法如下:
// 调用成功时
new Result().success(res)
new Result('登录成功').success(res)
// 调用成功时,包含参数
new Result({ token }, '登录成功').success(res)
// 调用失败时
new Result('用户名或密码不存在').fail(res)
1
2
3
4
5
6
7
2
3
4
5
6
7
← 搭建 https 服务 mysql →