-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path05-nested-fields.js
75 lines (69 loc) · 1.64 KB
/
05-nested-fields.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
import { withFields, string, number, boolean, fields } from "@commodo/fields";
// We've wrapped this code sample into an async function, so we can
// make function calls with the await keyword and make our code look nicer.
(async () => {
try {
const Stats = withFields({
views: number(),
books: number(),
awards: number({
validation: (value) => {
if (value < 0) {
throw new Error(
"Awards count must be greater than or equal to zero."
);
}
}
})
})();
const Author = withFields({
firstName: string(),
lastName: string(),
age: number({
validation: (value) => {
if (value < 25) {
throw new Error("Author must be at least 25 years old.");
}
}
}),
isFamous: boolean(),
stats: fields({
instanceOf: Stats,
validation: (value) => {
if (!value) {
throw new Error("Stats are required.");
}
}
})
})();
const author = new Author();
author.populate({
firstName: "John",
lastName: "Doe",
age: 25,
isFamous: false,
stats: {
views: 150,
books: 7,
awards: 1
}
});
const stats = new Stats();
stats.populate({
views: 150,
books: 7,
awards: -1
});
author.populate({
firstName: "John",
lastName: "Doe",
age: 25,
isFamous: false,
stats: stats
});
await author.validate();
} catch (e) {
console.log("Error message: ", e.message);
console.log("Error data: ", e.data);
}
})();