-
Notifications
You must be signed in to change notification settings - Fork 4
/
setters.js
93 lines (76 loc) · 1.5 KB
/
setters.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
// Suppose that we want to convert
// 0 -> 'MALE'
// 1 -> 'FEMALE'
// 2 -> 'SECRET'
import {type} from 'skema'
import {isNumber} from './multiple-validators'
const GENDERS = [
'MALE',
'FEMALE',
'SECRET'
]
// 1
// skema check validators, then process setters
const Gender = type({
validate: isNumber,
set (v) {
if (v in GENDERS) {
return GENDERS[v]
}
// And we could also throw errors in setters
// as we do in validators
throw 'invalid gender'
}
})
Gender.from('haha')
// throw Error
// - message: invalid value 'haha'
// - code: 'VALIDATION_FAILS'
Gender.from(1)
// 'FEMALE'
Gender.from(3)
// throw Error
// - message: 'invalid gender'
// - code: 'CUSTOM_ERROR'
// 2
// So we create our own Enum factory
export const Enum = (enums) => {
return type({
set (v) {
if (v in enums) {
return enums[v]
}
throw 'invalid enum'
}
})
}
const gender2 = Enum(GENDERS)
// 3
// Similar to validators, `set` could also be an array
const UserComment = type({
set: [
stripHTMLTags,
comment => `comment: ${comment}`
]
})
UserComment.from('I seem <script>doEvil()</script>innocent')
// 'comment: I seem innocent'
// 4.
// Async setters
import {defaults} from 'skema'
const {
type: asyncType
} = defaults({
async: true
})
const SpanishTranslator = asyncType({
set (v) {
return new Promise((resolve) => {
remoteGoogleTranslate(v, 'spanish', words => {
resolve(words)
})
})
}
})
SpanishTranslator.from('hello')
// hola