-
Notifications
You must be signed in to change notification settings - Fork 15
/
update.go
322 lines (271 loc) · 7.03 KB
/
update.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
package parse
import (
"encoding/json"
"errors"
"fmt"
"net/url"
"path"
"reflect"
)
type updateTypeT int
const (
opSet updateTypeT = iota
opIncr
opDelete
opAdd
opAddUnique
opRemove
opAddRelation
opRemoveRelation
)
func (u updateTypeT) String() string {
switch u {
case opSet:
return "Set"
case opIncr:
return "Increment"
case opDelete:
return "Delete"
case opAdd:
return "Add"
case opAddUnique:
return "AddUnique"
case opRemove:
return "Remove"
case opAddRelation:
return "AddRelation"
case opRemoveRelation:
return "RemoveRelation"
}
return "Unknown"
}
func (u updateTypeT) argKey() string {
switch u {
case opIncr:
return "amount"
case opAdd, opAddUnique, opRemove, opAddRelation, opRemoveRelation:
return "objects"
}
return "unknown"
}
type updateOpT struct {
UpdateType updateTypeT
Value interface{}
}
func (u updateOpT) MarshalJSON() ([]byte, error) {
switch u.UpdateType {
case opSet:
return json.Marshal(u.Value)
case opDelete:
return json.Marshal(map[string]interface{}{
"__op": u.UpdateType.String(),
})
default:
return json.Marshal(map[string]interface{}{
"__op": u.UpdateType.String(),
u.UpdateType.argKey(): u.Value,
})
}
}
type Update interface {
//Set the field specified by f to the value of v
Set(f string, v interface{}) Update
// Increment the field specified by f by the amount specified by v.
// v should be a numeric type
Increment(f string, v interface{}) Update
// Delete the field specified by f from the instance being updated
Delete(f string) Update
// Append the values provided to the Array field specified by f. This operation
// is atomic
Add(f string, vs ...interface{}) Update
// Add any values provided that were not alread present to the Array field
// specified by f. This operation is atomic
AddUnique(f string, vs ...interface{}) Update
// Remove the provided values from the array field specified by f
Remove(f string, vs ...interface{}) Update
// Update the ACL on the given object
SetACL(a ACL) Update
// Use the Master Key for this update request
UseMasterKey() Update
// Execute this update. This method also updates the proper fields
// on the provided value with their repective new values
Execute() error
requestT
}
type updateT struct {
inst interface{}
values map[string]updateOpT
shouldUseMasterKey bool
currentSession *sessionT
}
// Create a new update request for the Parse object represented by v.
//
// Note: v should be a pointer to a struct whose name represents a Parse class,
// or that implements the ClassName method
func NewUpdate(v interface{}) (Update, error) {
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Ptr || rv.IsNil() {
return nil, errors.New("v must be a non-nil pointer")
}
return &updateT{
inst: v,
values: map[string]updateOpT{},
}, nil
}
func (u *updateT) Set(f string, v interface{}) Update {
u.values[f] = updateOpT{UpdateType: opSet, Value: encodeForRequest(v)}
return u
}
func (u *updateT) Increment(f string, v interface{}) Update {
u.values[f] = updateOpT{UpdateType: opIncr, Value: v}
return u
}
func (u *updateT) Delete(f string) Update {
u.values[f] = updateOpT{UpdateType: opDelete}
return u
}
func (u *updateT) Add(f string, vs ...interface{}) Update {
u.values[f] = updateOpT{UpdateType: opAdd, Value: vs}
return u
}
func (u *updateT) AddUnique(f string, vs ...interface{}) Update {
u.values[f] = updateOpT{UpdateType: opAddUnique, Value: vs}
return u
}
func (u *updateT) Remove(f string, vs ...interface{}) Update {
u.values[f] = updateOpT{UpdateType: opRemove, Value: vs}
return u
}
func (u *updateT) SetACL(a ACL) Update {
u.values["ACL"] = updateOpT{UpdateType: opSet, Value: a}
return u
}
func (u *updateT) Execute() (err error) {
defer func() {
if r := recover(); r != nil {
if e, ok := r.(error); ok {
err = e
} else {
err = fmt.Errorf("error executing update: %v", r)
}
}
}()
rv := reflect.ValueOf(u.inst)
rvi := reflect.Indirect(rv)
fieldMap := getFieldNameMap(rv)
for k, v := range u.values {
var fname string
if fn, ok := fieldMap[k]; ok {
fname = fn
} else {
fname = k
}
fname = firstToUpper(fname)
dv := reflect.ValueOf(v.Value)
dvi := reflect.Indirect(dv)
if fv := rvi.FieldByName(fname); fv.IsValid() {
fvi := reflect.Indirect(fv)
switch v.UpdateType {
case opSet:
if fv.Kind() == reflect.Ptr && fv.IsNil() && v.Value != nil {
fv.Set(reflect.New(fv.Type().Elem()))
}
var tmp reflect.Value
if fv.Kind() == reflect.Ptr {
if v.Value == nil {
tmp = fv.Addr()
} else {
tmp = fv
}
} else {
tmp = fv.Addr()
}
if err := populateValue(tmp.Interface(), v.Value); err != nil {
return err
}
case opIncr:
switch fvi.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if dvi.Type().ConvertibleTo(fvi.Type()) {
current := fvi.Int()
amount := dvi.Convert(fvi.Type()).Int()
current += amount
fvi.Set(reflect.ValueOf(current).Convert(fvi.Type()))
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if dvi.Type().ConvertibleTo(fvi.Type()) {
current := fvi.Uint()
amount := dvi.Convert(fvi.Type()).Uint()
current += amount
fvi.Set(reflect.ValueOf(current).Convert(fvi.Type()))
}
case reflect.Float32, reflect.Float64:
if dvi.Type().ConvertibleTo(fvi.Type()) {
current := fvi.Float()
amount := dvi.Convert(fvi.Type()).Float()
current += amount
fvi.Set(reflect.ValueOf(current).Convert(fvi.Type()))
}
}
case opDelete:
fv.Set(reflect.Zero(fv.Type()))
}
}
}
if b, err := defaultClient.doRequest(u); err != nil {
return err
} else {
return handleResponse(b, u.inst)
}
}
func (u *updateT) UseMasterKey() Update {
u.shouldUseMasterKey = true
return u
}
func (u *updateT) method() string {
return "PUT"
}
func (u *updateT) endpoint() (string, error) {
_url := url.URL{}
p := getEndpointBase(u.inst)
rv := reflect.ValueOf(u.inst)
rvi := reflect.Indirect(rv)
if f := rvi.FieldByName("Id"); f.IsValid() {
if s, ok := f.Interface().(string); ok {
p = path.Join(p, s)
} else {
return "", fmt.Errorf("Id field should be a string, received type %s", f.Type())
}
} else {
return "", fmt.Errorf("can not update value - type has no Id field")
}
_url.Scheme = ParseScheme
_url.Host = parseHost
_url.Path = p
return _url.String(), nil
}
func (u *updateT) body() (string, error) {
b, err := json.Marshal(u.values)
if err != nil {
return "", err
}
return string(b), nil
}
func (u *updateT) useMasterKey() bool {
return u.shouldUseMasterKey
}
func (u *updateT) session() *sessionT {
return u.currentSession
}
func (u *updateT) contentType() string {
return "application/json"
}
func LinkFacebookAccount(u *User, a *FacebookAuthData) error {
if u.Id == "" {
return errors.New("user Id field must not be empty")
}
up, _ := NewUpdate(u)
up.Set("authData", AuthData{Facebook: a})
up.UseMasterKey()
return up.Execute()
}