-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path18-storage-hooks.js
71 lines (66 loc) · 1.94 KB
/
18-storage-hooks.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
const { withFields, string, boolean } = require("@commodo/fields");
const { pipe } = require("ramda");
const { withStorage } = require("@commodo/fields-storage");
const { withHooks } = require("@commodo/hooks");
const { withName } = require("@commodo/name");
const { NeDbDriver, withId } = require("@commodo/fields-storage-nedb");
const sendPasswordChangedEmail = async (email) => {
console.log(`Dear ${email}, your password has changed! Was that really you?`);
};
// 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 User = pipe(
withName("User"),
withId(),
withFields({
email: string(),
password: string(),
hasUnpaidBills: boolean()
}),
withHooks({
beforeUpdate() {
if (this.password) {
const remove = this.hook("afterSave", async () => {
remove();
await sendPasswordChangedEmail(this.email);
this.getField("password").reset();
});
}
}
}),
withStorage({
driver: new NeDbDriver()
}),
withHooks({
beforeSave() {},
afterSave() {},
beforeUpdate() {},
afterUpdate() {},
beforeCreate() {},
afterCreate() {}
}),
withHooks({
beforeDelete() {
if (this.hasUnpaidBills) {
throw new Error(
"Cannot delete the user - there are unpaid biils that need to be sorted first."
);
}
}
})
)();
const user = new User();
user.email = "[email protected]";
user.password = "12345678";
await user.save();
user.password = "87654321";
await user.save();
user.hasUnpaidBills = true;
await user.delete();
} catch (e) {
console.log("Error message: ", e.message);
console.log("Error data: ", e.data);
}
})();