-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrategy.go
More file actions
74 lines (61 loc) · 2.2 KB
/
strategy.go
File metadata and controls
74 lines (61 loc) · 2.2 KB
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
package speedrail
import "context"
// Strategy is a function that will be executed.
type Strategy[C, M any] func(context.Context, C, M) (context.Context, M, Error)
// If executes a strategy if the condition is true.
func If[C, M any](condition Condition[M], onTrue Strategy[C, M]) Strategy[C, M] {
return func(ctx context.Context, container C, model M) (context.Context, M, Error) {
if condition(model) {
return onTrue(ctx, container, model)
}
return ctx, model, nil
}
}
// IfElse executes a strategy if the condition is true, otherwise execute another strategy.
func IfElse[C, M any](condition Condition[M], onTrue Strategy[C, M], onFalse Strategy[C, M]) Strategy[C, M] {
return func(ctx context.Context, container C, model M) (context.Context, M, Error) {
if condition(model) {
return onTrue(ctx, container, model)
}
return onFalse(ctx, container, model)
}
}
// Merge executes all strategies and will not stop on error, but merge all errors together and then return any error.
func Merge[C, M any](strategies ...Strategy[C, M]) Strategy[C, M] {
return func(ctx context.Context, container C, model M) (context.Context, M, Error) {
var resultErr Error
for _, strategy := range strategies {
var err Error
ctx, model, err = strategy(ctx, container, model)
if err == nil {
continue
}
if resultErr == nil {
resultErr = err
continue
}
resultErr = resultErr.Merge(err)
}
return ctx, model, resultErr
}
}
// Group is a helper function that makes it easier to read strategies logically grouped together. They are executed in
// order. If an error is returned, the execution of the strategies will stop and error returned.
func Group[C, M any](strategies ...Strategy[C, M]) Strategy[C, M] {
return func(ctx context.Context, container C, model M) (context.Context, M, Error) {
for _, strategy := range strategies {
var err Error
ctx, model, err = strategy(ctx, container, model)
if err != nil {
return ctx, model, err
}
}
return ctx, model, nil
}
}
// ThrowError will return a defined error.
func ThrowError[C, M any](err Error) Strategy[C, M] {
return func(ctx context.Context, container C, model M) (context.Context, M, Error) {
return ctx, model, err
}
}