-
Notifications
You must be signed in to change notification settings - Fork 5
/
async-validation.js
105 lines (80 loc) 路 2.03 KB
/
async-validation.js
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// By default, skema works synchronously.
// To make the validators works asynchronously,
// we should change the default settings
import {defaults} from 'skema'
const {
type
} = defaults({
async: true
})
// And then:
// - `validate` could be an async function
// - even sync method `validate` also works asynchronously
// 1
const PositiveNumber = type({
validate (v) {
if (typeof v !== 'number') {
reutrn false
}
if (v > 0) {
return true
}
throw 'must be positive'
}
})
PositiveNumber.from(1) // Promise{1}
PositiveNumber.from(1).then(console.log) // prints 1
PositiveNumber.from('1').catch(console.error) // prints Error
PositiveNumber.from(-1)
// Unhandled Promise rejection
PositiveNumber.from(-1).catch(console.error)
// Error
// - code: 'CUSTOM_ERROR'
// - message: 'must be positive'
// 2
// Real async valdidator
const BigNumber = type({
validate (v) {
return new Promise((resolve, reject) => {
if (typeof v !== 'number') {
return reject('not a number')
}
if (v <= 0) {
return reject('must be positive')
}
if (v < 10000) {
// resolve `false` also indicates a failure
return resolve(false)
}
resolve(true)
})
}
})
const printErrorMessage = err =>
err && console.error(err.message, err.code)
BigNumber.from(-1).catch(printErrorMessage)
// 'must be positive' 'CUSTOM_ERROR'
BigNumber.from('-1').catch(printErrorMessage)
// 'not a number' 'CUSTOM_ERROR'
BigNumber.from(1).catch(printErrorMessage)
// 'invalid value 1' 'VALIDATION_FAILS'
BigNumber.from(10000).then(console.log)
// 10000
// 3
// Duplex: return value with Promise.reject/resolve
const BigNumber2 = type({
validate (v) {
if (typeof v !== 'number') {
return Promise.reject('not a number')
}
if (v <= 0) {
return Promise.reject('must be positive')
}
if (v < 10000) {
// resolve `false` also indicates a failure
return Promise.resolve(false)
}
return true
}
})
// The same effect as `BigNumber`