-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreferences.go
53 lines (41 loc) · 990 Bytes
/
references.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
package gorm_fixtures
import (
"context"
"errors"
"log"
"sync"
)
const ReferenceCtxKey = "_reference_"
var ErrReferenceNotFound = errors.New("reference not found")
type LoadCtx struct {
ctx context.Context
references map[string]interface{}
mu *sync.RWMutex
}
func NewLoadCtx(ctx context.Context) *LoadCtx {
return &LoadCtx{ctx: ctx, references: make(map[string]interface{}), mu: &sync.RWMutex{}}
}
func (l *LoadCtx) Context() context.Context {
return l.ctx
}
func (l *LoadCtx) MustGetReference(id string) interface{} {
v, err := l.GetReference(id)
if err != nil {
log.Fatalf("reference %s not found", id)
}
return v
}
func (l *LoadCtx) GetReference(id string) (interface{}, error) {
l.mu.RLock()
defer l.mu.RUnlock()
val, exists := l.references[id]
if !exists {
return nil, ErrReferenceNotFound
}
return val, nil
}
func (l *LoadCtx) SetReference(id string, value interface{}) {
l.mu.Lock()
defer l.mu.Unlock()
l.references[id] = value
}