-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
register.go
110 lines (82 loc) · 1.86 KB
/
register.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
101
102
103
104
105
106
107
108
109
110
package goriak
import (
"encoding/json"
"errors"
riak "github.com/basho/riak-go-client"
)
func NewRegister() *Register {
return &Register{}
}
type Register struct {
helper
val []byte
}
func (r *Register) Value() []byte {
return r.val
}
func (r *Register) String() string {
return string(r.val)
}
func (r *Register) Set(val []byte) *Register {
r.val = val
return r
}
func (r *Register) SetString(val string) *Register {
r.val = []byte(val)
return r
}
func (r *Register) Exec(client *Session) error {
if r == nil {
return errors.New("Nil Register")
}
if r.name == "" {
return errors.New("Unknown path to Register. Retrieve Register with Get or Set before updating the Register")
}
// Validate s.key
if r.key.bucket == "" || r.key.bucketType == "" || r.key.key == "" {
return errors.New("Invalid key in Register Exec()")
}
op := &riak.MapOperation{}
outerOp := op
// Traverse c.path so that we increment the correct counter in nested maps
for _, subMapName := range r.path {
op = op.Map(subMapName)
}
op.SetRegister(r.name, r.val)
cmd, err := riak.NewUpdateMapCommandBuilder().
WithBucket(r.key.bucket).
WithBucketType(r.key.bucketType).
WithKey(r.key.key).
WithMapOperation(outerOp).
WithContext(r.context).
Build()
if err != nil {
return err
}
err = client.riak.Execute(cmd)
if err != nil {
return err
}
res, ok := cmd.(*riak.UpdateMapCommand)
if !ok {
return errors.New("Could not convert")
}
if !res.Success() {
return errors.New("Not successful")
}
return nil
}
// MarshalJSON satisfies the JSON interface
func (r Register) MarshalJSON() ([]byte, error) {
return json.Marshal(r.val)
}
// UnmarshalJSON satisfies the JSON interface
func (r *Register) UnmarshalJSON(data []byte) error {
var values []byte
err := json.Unmarshal(data, &values)
if err != nil {
return err
}
r.val = values
return nil
}