-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
50 lines (44 loc) · 1.37 KB
/
context.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
package databuilder
import "context"
// key our custom type to avoid collision with other packages using context
type key string
const (
// pKey is the key used to store Result obj in context
pKey key = "github.com/coldebrew-go/data-builder.Result"
)
// AddResultToCtx adds the given result object to context
//
// this function should ideally only be used in your tests and/or for debugging
// modification made to Result obj will NOT persist
func AddResultToCtx(ctx context.Context, r Result) context.Context {
if ctx == nil {
ctx = context.Background()
}
return context.WithValue(ctx, pKey, r)
}
// GetResultFromCtx gives access to result object at this point in execution
//
// this function should ideally only be used in your tests and/or for debugging
// modification made to Result obj may or may not persist
func GetResultFromCtx(ctx context.Context) Result {
v := ctx.Value(pKey)
if v == nil {
return nil
}
if r, ok := v.(Result); ok {
return r
}
return nil
}
// GetFromResult allows builders to access data built by other builders
//
// this function enables optional access to data, your code should not rely on
// values being present, if you have explicit dependency please add them to your
// function parameters
func GetFromResult(ctx context.Context, obj interface{}) interface{} {
r := GetResultFromCtx(ctx)
if r == nil {
return nil
}
return r.Get(obj)
}