-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoption.go
58 lines (51 loc) · 1.24 KB
/
option.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package pipes
import (
"context"
"errors"
"time"
)
var (
ErrSkip = errors.New("handler was skipped")
ErrCriticalPath = errors.New("failure on critical path")
)
type Option[S Store] func(Handler[S]) Handler[S]
func WithTimeout[S Store](timeout time.Duration) Option[S] {
return func(next Handler[S]) Handler[S] {
return func(ctx context.Context, s S) (any, error) {
ctx, cancelFn := context.WithTimeout(ctx, timeout)
defer cancelFn()
return next(ctx, s)
}
}
}
func WithCondition[S Store](skip bool) Option[S] {
return func(next Handler[S]) Handler[S] {
return func(ctx context.Context, s S) (any, error) {
if skip {
return nil, ErrSkip
}
return next(ctx, s)
}
}
}
func WithCriticalPath[S Store]() Option[S] {
return func(next Handler[S]) Handler[S] {
return func(ctx context.Context, s S) (any, error) {
data, err := next(ctx, s)
if err != nil {
return data, errors.Join(ErrCriticalPath, err)
}
return data, err
}
}
}
func WithRunAfter[S Store](handlerIds ...int) Option[S] {
return func(next Handler[S]) Handler[S] {
return func(ctx context.Context, s S) (any, error) {
for i := 0; i < len(handlerIds); i++ {
_, _ = s.Read(ctx, handlerIds[i])
}
return next(ctx, s)
}
}
}