-
Notifications
You must be signed in to change notification settings - Fork 0
/
hooks.go
42 lines (36 loc) · 919 Bytes
/
hooks.go
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
package dal
import (
"context"
"fmt"
)
type ValidatableRecord interface {
Validate() error
}
var beforeSafeHooks []RecordHook
func BeforeSave(ctx context.Context, db DB, record Record) error {
if err := beforeSafe(ctx, db, record); err != nil {
return err
}
return callRecordHooks(ctx, record, beforeSafeHooks)
}
func callRecordHooks(ctx context.Context, record Record, hooks []RecordHook) error {
//errs := make([]error, 0, len(hooks))
for _, hook := range hooks {
if err := hook(ctx, record); err != nil {
return fmt.Errorf("%w: %v", ErrHookFailed, err)
}
}
//if len(errs) > 0 {
// return fmt.Errorf("%w: %v", ErrHookFailed, errors.Join(errs...))
//}
return nil
}
func beforeSafe(_ context.Context, _ DB, record Record) error {
data := record.Data()
if validatable, ok := data.(ValidatableRecord); ok {
if err := validatable.Validate(); err != nil {
return err
}
}
return nil
}