-
Notifications
You must be signed in to change notification settings - Fork 2
/
context.go
82 lines (63 loc) · 1.67 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
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
package digo
import (
"encoding/json"
"errors"
"io/ioutil"
"os"
)
type Context struct {
injector *Injector
cache map[string]interface{} `json:"-"`
NodeMap map[string]*NodeData `json:"nodes"`
}
func (this *Context) unmarshal(filePath string) error {
data, err := this.getFileBytes(filePath)
if err != nil {
return errors.New("Error getting file data -> " + err.Error())
}
err = json.Unmarshal(data, this)
if err != nil {
return errors.New("Error unmarshaling data -> " + err.Error())
}
this.cache = map[string]interface{}{}
this.injector = NewInjector(this.NodeMap)
return nil
}
func (this *Context) getFileBytes(filePath string) ([]byte, error) {
file, err := os.Open(filePath)
if err != nil {
return nil, errors.New("Error opening file -> " + err.Error())
}
fileBytes, err := ioutil.ReadAll(file)
if err != nil {
return nil, errors.New("Error reading file -> " + err.Error())
}
return fileBytes, nil
}
func (this *Context) memoize(key string, node *NodeData) (interface{}, error) {
if cached, exists := this.cache[key]; exists {
return cached, nil
}
t, err := this.injector.resolve(node, key)
if err != nil {
return t, err
}
this.cache[key] = t
return t, nil
}
func (this *Context) Get(key string) (interface{}, error) {
node, err := this.getFromNodeMap(key)
if err != nil {
return struct{}{}, err
}
return this.injector.resolve(node, key)
}
func (this *Context) getFromNodeMap(key string) (*NodeData, error) {
var node *NodeData
if tmpNode, exists := this.NodeMap[key]; exists {
node = tmpNode
} else {
return nil, errors.New("The given type cannot be found: " + key + " (forgot to add to the TypeRegister?)")
}
return node, nil
}