forked from ianstormtaylor/superstruct
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdefault-values.js
49 lines (43 loc) · 874 Bytes
/
default-values.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
import { struct } from 'superstruct'
// Define an auto-incrementing unique id.
let uid = 1
// Define a struct to validate with.
const User = struct(
{
id: 'number',
name: 'string',
email: 'string',
age: 'number',
is_admin: 'boolean?',
created_at: 'date',
},
{
id: () => uid++,
is_admin: false,
age: 0,
created_at: () => new Date(),
}
)
// Define data to be validated.
const data = {
name: 'Jane Smith',
email: '[email protected]',
age: 42,
}
// Validate the data and store the return value in the `user` variable. Any
// property that wasn't defined will be set to its default.
let user
try {
user = User(data)
console.log('Valid!', user)
} catch (e) {
throw e
}
// 'Valid!' {
// id: 0,
// name: 'Jane Smith',
// email: '[email protected]',
// age: 42,
// is_admin: false,
// created_at: Date,
// }