-
Notifications
You must be signed in to change notification settings - Fork 0
/
state.go
94 lines (84 loc) · 1.78 KB
/
state.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package state
import "context"
// CtxKeyType is a type that can be used as a key for a context.Context
type CtxKeyType string
// State is a type that can be used to store data in a context.Context
// It is useful for storing data that needs to be shared between tests
type State[T any] struct {
CtxKey CtxKeyType
}
// StateOption is a type that can be used to configure a State
type StateOption[T any] func(*State[T])
// WithCtxKey is a StateOption that sets the key for the context.Context
//
// Default: default
//
// Example:
//
// type test struct {
// Name string
// }
//
// state := state.NewState[test](
// state.WithCtxKey("test"),
// )
func WithCtxKey[T any](ctxKey CtxKeyType) StateOption[T] {
return func(state *State[T]) {
state.CtxKey = ctxKey
}
}
// NewState creates a new State
//
// Example:
//
// type test struct {
// Name string
// }
//
// state := state.NewState[test]()
func NewState[T any](opts ...StateOption[T]) *State[T] {
state := &State[T]{
CtxKey: "default",
}
for _, opt := range opts {
opt(state)
}
return state
}
// Enrich enriches the context with the data
//
// Example:
//
// type test struct {
// Name string
// }
//
// state := state.NewState[test]()
// ctx := state.Enrich(ctx, &test{
// Name: "John",
// })
func (state *State[T]) Enrich(ctx context.Context, data *T) context.Context {
return context.WithValue(ctx, state.CtxKey, data)
}
// Retrieve retrieves the data from the context
//
// Example:
//
// type test struct {
// Name string
// }
//
// state := state.NewState[test]()
// ctx := state.Enrich(ctx, &test{
// Name: "John",
// })
// data := state.Retrieve(ctx)
//
// fmt.Println(data.Name) // John
func (state *State[T]) Retrieve(ctx context.Context) *T {
data, ok := ctx.Value(state.CtxKey).(*T)
if !ok {
return new(T)
}
return data
}