/
service.go
100 lines (83 loc) · 2.11 KB
/
service.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
95
96
97
98
99
100
package data_repository
import (
"encoding/json"
"fmt"
"sync"
templateTY "github.com/jkandasa/autoeasy/pkg/types/template"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
"go.uber.org/zap"
)
const (
actionAdd = "add"
actionDelete = "delete"
)
var (
store = make(map[string]interface{})
mutex = sync.RWMutex{}
)
func Add(key string, value interface{}) {
mutex.Lock()
defer mutex.Unlock()
update(actionAdd, key, value)
}
func Delete(key string) {
mutex.Lock()
defer mutex.Unlock()
update(actionDelete, key, nil)
}
func Get(key string) interface{} {
mutex.RLock()
defer mutex.RUnlock()
jsonBytes, err := json.Marshal(store)
if err != nil {
zap.L().Error("error on marshalling store value", zap.Error(err))
}
result := gjson.GetBytes(jsonBytes, key)
return result.Value()
}
func update(action, key string, value interface{}) {
jsonBytes, err := json.Marshal(store)
if err != nil {
zap.L().Error("error on marshalling store value", zap.Error(err))
}
switch action {
case actionAdd:
jsonBytesUpdated, err := sjson.SetBytes(jsonBytes, key, value)
if err != nil {
zap.L().Error("error on updating value", zap.String("key", key), zap.Error(err))
}
jsonBytes = jsonBytesUpdated
case actionDelete:
jsonBytesUpdated, err := sjson.DeleteBytes(jsonBytes, key)
if err != nil {
zap.L().Error("error on deleting value", zap.String("key", key), zap.Error(err))
}
jsonBytes = jsonBytesUpdated
}
err = json.Unmarshal(jsonBytes, &store)
if err != nil {
zap.L().Error("error on unmarshalling store value", zap.Error(err))
}
}
func GetValue(key string, input interface{}) interface{} {
jsonBytes, err := json.Marshal(input)
if err != nil {
zap.L().Error("error on marshalling input value", zap.String("key", key), zap.Error(err))
}
result := gjson.GetBytes(jsonBytes, key)
return result.Value()
}
func AddWithStore(store templateTY.Store, value interface{}) {
if store.Key == "" {
return
}
newValue := value
if store.Query != "" {
newValue = GetValue(store.Query, value)
}
if store.Format != "" {
newValue = fmt.Sprintf(store.Format, newValue)
}
Add(store.Key, newValue)
}