/
record.go
509 lines (422 loc) · 13.7 KB
/
record.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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
package filemaker
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"mime"
"mime/multipart"
"net/http"
"reflect"
"strconv"
"strings"
)
//Record interface for some magic with methods
type Record struct {
ID string
Layout string
StagedChanges map[string]interface{}
FieldData map[string]interface{}
Session *Session
}
//newRecord returns a new instance of an existing record
func newRecord(layout string, data interface{}, session Session) Record {
return Record{
ID: data.(map[string]interface{})["recordId"].(string),
Layout: layout,
StagedChanges: make(map[string]interface{}),
FieldData: data.(map[string]interface{})["fieldData"].(map[string]interface{}),
Session: &session,
}
}
//SetField sets the value of a specified field in the given record
func (r *Record) SetField(fieldName string, value interface{}) {
switch value.(type) {
case int:
value = float64(value.(int))
case int32:
value = float64(value.(int32))
case int64:
value = float64(value.(int64))
case float32:
value = float64(value.(float32))
case float64:
value = float64(value.(float64))
case bool:
if value.(bool) {
value = float64(1)
} else {
value = float64(0)
}
}
r.StagedChanges[fieldName] = value
}
//GetField gets the value of a field in the given record and returns it as an `interface{}`
func (r *Record) GetField(fieldName string) interface{} {
if val, ok := r.StagedChanges[fieldName]; ok {
return val
}
return r.FieldData[fieldName]
}
//Revert discards all uncommited changes made to the record
func (r *Record) Revert() {
r.StagedChanges = make(map[string]interface{})
}
//Commit commits the changes made to the record using the same session the record was retrieved/created with
func (r *Record) Commit() error {
if len(r.StagedChanges) == 0 {
return nil
}
if r.ID == "" {
return r.Create()
}
var jsonData = struct {
FieldData map[string]interface{} `json:"fieldData"`
}{
r.StagedChanges,
}
//Create the request json body
var requestBody, err = json.Marshal(jsonData)
if err != nil {
return fmt.Errorf("failed to marshal request body: %v", err.Error())
}
//Build and send request to the host
req, err := http.NewRequest("PATCH", r.Session.Protocol+r.Session.Host+"/fmi/data/v1/databases/"+r.Session.Database+"/layouts/"+r.Layout+"/records/"+r.ID, bytes.NewBuffer(requestBody))
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", "Bearer "+r.Session.Token)
res, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("failed to send PATCH request: %v", err.Error())
}
//Read the body
resBodyBytes, err := ioutil.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %v", err.Error())
}
//Unmarshal json body
var jsonRes ResponseBody
err = json.Unmarshal(resBodyBytes, &jsonRes)
if err != nil {
return fmt.Errorf("failed to decode response body as json: %v", err.Error())
}
if jsonRes.Messages[0].Code != "0" {
return fmt.Errorf("failed at host: %v (%v)", jsonRes.Messages[0].Message, jsonRes.Messages[0].Code)
}
for fieldName, value := range r.StagedChanges {
r.FieldData[fieldName] = value
}
return nil
}
//CommitToContainer commits the specified bytes buffer to the specified container field in the record.
func (r *Record) CommitToContainer(fieldName string, filename string, dataBuf bytes.Buffer) error {
if r.ID == "" {
return errors.New("Record needs to be created first")
}
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
fw, err := writer.CreateFormFile("upload", filename)
if err != nil {
return errors.New("failed to write to field 'upload'")
}
//Build multipart/form-data header for request
if _, err := io.Copy(fw, &dataBuf); err != nil {
return err
}
if err := writer.Close(); err != nil {
return err
}
//Build and send request to the host
req, err := http.NewRequest("POST", r.Session.Protocol+r.Session.Host+"/fmi/data/v1/databases/"+r.Session.Database+"/layouts/"+r.Layout+"/records/"+r.ID+"/containers/"+fieldName, body)
cd := mime.FormatMediaType("attachment", map[string]string{"filename": filename})
req.Header.Set("Content-Disposition", cd)
req.Header.Set("Content-Type", writer.FormDataContentType())
req.Header.Add("Authorization", "Bearer "+r.Session.Token)
res, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("failed to send POST request: %v", err.Error())
}
//Read the body
resBodyBytes, err := ioutil.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %v", err.Error())
}
// //Unmarshal json body
jsonRes := &ResponseBody{}
if err := json.Unmarshal(resBodyBytes, &jsonRes); err != nil {
return fmt.Errorf("failed to decode response body as json: %v", err.Error())
}
if jsonRes.Messages[0].Code != "0" {
return fmt.Errorf("failed at host: %v (%v)", jsonRes.Messages[0].Message, jsonRes.Messages[0].Code)
}
return nil
}
//CommitFileToContainer commits the specified file to specified container field in the record
func (r *Record) CommitFileToContainer(fieldName, filepath string) error {
//Record is empty and not created yet
if r.ID == "" {
return errors.New("record needs to be created first")
}
b, err := ioutil.ReadFile(filepath)
if err != nil {
return fmt.Errorf("failed to read file: %v", err)
}
buf := bytes.NewBuffer(b)
pathSlice := strings.Split(filepath, "/")
filename := pathSlice[len(pathSlice)-1]
return r.CommitToContainer(fieldName, filename, *buf)
}
//Create inserts the record into the database if it doesn't exist
func (r *Record) Create() error {
var jsonData = struct {
FieldData map[string]interface{} `json:"fieldData"`
}{
r.StagedChanges,
}
//Create the request json body
var requestBody, err = json.Marshal(jsonData)
if err != nil {
return fmt.Errorf("failed to marshal request body: %v", err.Error())
}
//Build and send request to the host to create record
req, err := http.NewRequest("POST", r.Session.Protocol+r.Session.Host+"/fmi/data/v1/databases/"+r.Session.Database+"/layouts/"+r.Layout+"/records", bytes.NewBuffer(requestBody))
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", "Bearer "+r.Session.Token)
res, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("failed to send POST request: %v", err.Error())
}
//Read the body
resBodyBytes, err := ioutil.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %v", err.Error())
}
//Unmarshal json body
var jsonRes ResponseBody
err = json.Unmarshal(resBodyBytes, &jsonRes)
if err != nil {
return fmt.Errorf("failed to decode response body as json: %v", err.Error())
}
//Check for errors in the response
if jsonRes.Messages[0].Code != "0" {
return fmt.Errorf("failed at host: %v (%v)", jsonRes.Messages[0].Message, jsonRes.Messages[0].Code)
}
//Update local record field data with staged changes
for fieldName, value := range r.StagedChanges {
r.FieldData[fieldName] = value
}
//Set the ID returned by the API
r.ID = jsonRes.Response.RecordID
//Build and send request to the host to get the default field data for the created record
req, err = http.NewRequest("GET", r.Session.Protocol+r.Session.Host+"/fmi/data/v1/databases/"+r.Session.Database+"/layouts/"+r.Layout+"/records/"+r.ID, bytes.NewBuffer([]byte{}))
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", "Bearer "+r.Session.Token)
res, err = http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("failed to send GET request: %v", err.Error())
}
//Read the body
resBodyBytes, err = ioutil.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %v", err.Error())
}
//Unmarshal json body
err = json.Unmarshal(resBodyBytes, &jsonRes)
if err != nil {
return fmt.Errorf("failed to decode response body as json: %v", err.Error())
}
//Check for errors in the response
if jsonRes.Messages[0].Code != "0" {
return fmt.Errorf("failed at host: %v (%v)", jsonRes.Messages[0].Message, jsonRes.Messages[0].Code)
}
//Parse the field data for the record
for fieldname, val := range jsonRes.Response.Data[0].(map[string]interface{})["fieldData"].(map[string]interface{}) {
r.FieldData[fieldname] = val
}
return nil
}
//Delete deletes the record using the same session the record was retrieved with
func (r *Record) Delete() error {
//Build and send request to the host
req, err := http.NewRequest("DELETE", r.Session.Protocol+r.Session.Host+"/fmi/data/v1/databases/"+r.Session.Database+"/layouts/"+r.Layout+"/records/"+r.ID, bytes.NewBuffer([]byte{}))
req.Header.Add("Authorization", "Bearer "+r.Session.Token)
res, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("failed to send DELETE request: %v", err.Error())
}
//Read the body
resBodyBytes, err := ioutil.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("failed to read respones body: %v", err.Error())
}
//Unmarshal json body
var jsonRes ResponseBody
err = json.Unmarshal(resBodyBytes, &jsonRes)
if err != nil {
return fmt.Errorf("failed to decode response body as json: %v", err.Error())
}
if jsonRes.Messages[0].Code != "0" {
return fmt.Errorf("failed at host: %v (%v)", jsonRes.Messages[0].Message, jsonRes.Messages[0].Code)
}
//Empty the local record instance
r.ID = ""
r.StagedChanges = map[string]interface{}{}
r.FieldData = map[string]interface{}{}
return nil
}
/*
String gets the data in the specified field and returns it as a string.
The FileMaker database field needs to be a text field.
*/
func (r *Record) String(fieldName string) (string, error) {
data := r.GetField(fieldName)
switch data.(type) {
case string:
return data.(string), nil
case int:
return strconv.FormatInt(int64(data.(int)), 10), nil
case int16:
return strconv.FormatInt(int64(data.(int16)), 10), nil
case int32:
return strconv.FormatInt(int64(data.(int32)), 10), nil
case int64:
return strconv.FormatInt(int64(data.(int64)), 10), nil
case float32:
return strconv.FormatFloat(float64(data.(float32)), 'f', -1, 32), nil
case float64:
return strconv.FormatFloat(data.(float64), 'f', -1, 64), nil
case nil:
return "", nil
}
return "", fmt.Errorf("field `%v` could not be asserted as or converted to string: %v", fieldName, data)
}
/*
Int gets the data in the specified field and returns it as an int.
The FileMaker database field needs to be a number field.
*/
func (r *Record) Int(fieldName string) (int, error) {
data := r.GetField(fieldName)
if val, ok := data.(float64); ok {
return int(val), nil
}
return 0, fmt.Errorf("field `%v` value is not of type int: %v", fieldName, data)
}
/*
Int32 gets the data in the specified field and returns it as an int32.
The FileMaker database field needs to be a number field.
*/
func (r *Record) Int32(fieldName string) (int32, error) {
data := r.GetField(fieldName)
if val, ok := data.(float64); ok {
return int32(val), nil
}
return 0, fmt.Errorf("field `%v` value is not of type int32: %v", fieldName, data)
}
/*
Int64 gets the data in the specified field and returns it as an int64.
The FileMaker database field needs to be a number field.
*/
func (r *Record) Int64(fieldName string) (int64, error) {
data := r.GetField(fieldName)
if val, ok := data.(float64); ok {
return int64(val), nil
}
return 0, fmt.Errorf("field `%v` value is not of type int64: %v", fieldName, data)
}
/*
Float32 gets the data in the specified field and returns it as an float32.
The FileMaker database field needs to be a number field.
*/
func (r *Record) Float32(fieldName string) (float32, error) {
data := r.GetField(fieldName)
if val, ok := data.(float64); ok {
return float32(val), nil
}
return 0, fmt.Errorf("field `%v` value is not of type float32: %v", fieldName, data)
}
/*
Float64 gets the data in the specified field and returns it as an float64.
The FileMaker database field needs to be a number field.
*/
func (r *Record) Float64(fieldName string) (float64, error) {
data := r.GetField(fieldName)
if val, ok := data.(float64); ok {
return val, nil
}
return 0, fmt.Errorf("field `%v` value is not of type float64: %v", fieldName, data)
}
/*
Bool gets the data in the specified field and returns it as an bool.
The FileMaker database field needs to be a number field. Numbers
larger than `0` return `true` and `0` or below returns `false`.
*/
func (r *Record) Bool(fieldName string) (bool, error) {
data := r.GetField(fieldName)
switch data.(type) {
case string:
return len(data.(string)) > 0, nil
case float64:
return data.(float64) > 0, nil
case nil:
return false, nil
}
return false, fmt.Errorf("field `%v` value is not of type bool: %v", fieldName, data)
}
/*
Map takes a struct and inserts the field data of the record
in the struct fields with an `fm`-tag matching the record field name.
Example struct:
`
type example struct {
Name string `fm:"Name"`
Age int `fm:"Age"`
}
`
- A pointer to the object must be passed (i.e `Record.Map(&obj)`).
- Nested structs are not supported.
Supported types:
- string
- int
- int64
- float64
- bool
*/
func (r *Record) Map(obj interface{}) error {
v := reflect.Indirect(reflect.ValueOf(obj))
typeOfObj := v.Type()
for i := 0; i < v.NumField(); i++ {
field := v.Field(i)
if !field.IsValid() || !field.CanSet() {
continue
}
tag := typeOfObj.Field(i).Tag.Get("fm")
switch field.Interface().(type) {
case string:
val, err := r.String(tag)
if err != nil {
return err
}
field.SetString(val)
case int, int64:
val, err := r.Int64(tag)
if err != nil {
return err
}
field.SetInt(val)
case float64:
val, err := r.Float64(tag)
if err != nil {
return err
}
field.SetFloat(val)
case bool:
val, err := r.Bool(tag)
if err != nil {
return err
}
field.SetBool(val)
}
}
return nil
}