-
Notifications
You must be signed in to change notification settings - Fork 1
/
record.go
686 lines (569 loc) · 16.9 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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
package filemaker
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"mime"
"mime/multipart"
"net/http"
"reflect"
"regexp"
"strings"
"time"
)
// 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,
}
}
// Set sets the value of a specified field in the given record
func (r *Record) Set(fieldName string, value interface{}) {
switch value.(type) {
case int:
value = float64(value.(int))
case int8:
value = float64(value.(int8))
case int16:
value = float64(value.(int16))
case int32:
value = float64(value.(int32))
case int64:
value = float64(value.(int64))
case float32:
value = float64(value.(float32))
case bool:
if value.(bool) {
value = float64(1)
} else {
value = float64(0)
}
}
r.StagedChanges[fieldName] = value
}
// Get gets the value of a field in the given record and returns it as an `interface{}`
func (r *Record) Get(fieldName string) interface{} {
if val, ok := r.StagedChanges[fieldName]; ok {
return val
}
return r.FieldData[fieldName]
}
// Reset discards all uncommited changes made to the record
func (r *Record) Reset() {
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.recordsURL(r.Layout, 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, 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",
fmt.Sprintf(
"%s/containers/%s",
r.Session.recordsURL(r.Layout, r.ID),
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.recordsURL(r.Layout, ""),
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.recordsURL(r.Layout, 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.recordsURL(r.Layout, 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 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 response code
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
}
// StringE behaves like String but returns ErrNotString if the value is not a string.
func (r Record) StringE(fieldName string) (string, error) {
data := r.Get(fieldName)
if reflect.ValueOf(data).Kind() == reflect.String {
return data.(string), nil
}
return "", ErrNotString
}
/*
String gets the data in the specified field and returns it as a string.
The FileMaker database field needs to be a text field. Ignores any errors.
*/
func (r Record) String(fieldName string) string {
s, _ := r.StringE(fieldName)
return s
}
// IntE behaves like Int but returns ErrNotNumber if the value is not a number.
func (r Record) IntE(fieldName string) (int, error) {
data := r.Get(fieldName)
if val, ok := data.(float64); ok {
return int(val), nil
}
return 0, ErrNotNumber
}
/*
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 {
i, _ := r.IntE(fieldName)
return i
}
// Int8E behaves like Int8 but returns ErrNotNumber if the value is not a number.
func (r Record) Int8E(fieldName string) (int8, error) {
data := r.Get(fieldName)
if val, ok := data.(float64); ok {
return int8(val), nil
}
return 0, ErrNotNumber
}
/*
Int8 gets the data in the specified field and returns it as an int8.
The FileMaker database field needs to be a number field.
*/
func (r *Record) Int8(fieldName string) int8 {
i, _ := r.Int8E(fieldName)
return i
}
// Int16E behaves like Int16 but returns ErrNotNumber if the value is not a number.
func (r Record) Int16E(fieldName string) (int16, error) {
data := r.Get(fieldName)
if val, ok := data.(float64); ok {
return int16(val), nil
}
return 0, ErrNotNumber
}
/*
Int16 gets the data in the specified field and returns it as an int16.
The FileMaker database field needs to be a number field.
*/
func (r *Record) Int16(fieldName string) int16 {
i, _ := r.Int16E(fieldName)
return i
}
// Int32E behaves like Int32 but returns ErrNotNumber if the value is not a number.
func (r Record) Int32E(fieldName string) (int32, error) {
data := r.Get(fieldName)
if val, ok := data.(float64); ok {
return int32(val), nil
}
return 0, ErrNotNumber
}
/*
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 {
i, _ := r.Int32E(fieldName)
return i
}
// Int64E behaves like Int64 but returns ErrNotNumber if the value is not a number.
func (r Record) Int64E(fieldName string) (int64, error) {
data := r.Get(fieldName)
if val, ok := data.(float64); ok {
return int64(val), nil
}
return 0, ErrNotNumber
}
/*
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 {
i, _ := r.Int64E(fieldName)
return i
}
// Float32E behaves like Float32 but returns ErrNotNumber if the value is not a number.
func (r Record) Float32E(fieldName string) (float32, error) {
data := r.Get(fieldName)
if val, ok := data.(float64); ok {
return float32(val), nil
}
return 0, ErrNotNumber
}
/*
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 {
i, _ := r.Float32E(fieldName)
return i
}
// Float64E behaves like Float64 but returns ErrNotNumber if the value is not a number.
func (r Record) Float64E(fieldName string) (float64, error) {
data := r.Get(fieldName)
if val, ok := data.(float64); ok {
return val, nil
}
return 0, ErrNotNumber
}
/*
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 {
i, _ := r.Float64E(fieldName)
return i
}
/*
Bool gets the data in the specified field and parses it as a bool, with empty
fields evaluating to `false` and non-empty text fields and number fields with
a value greater than 0 evaluating to `true`.
*/
func (r *Record) Bool(fieldName string) bool {
data := r.Get(fieldName)
switch data.(type) {
case string:
return len(data.(string)) > 0
case float64:
return data.(float64) > 0
}
return false
}
/*
TimeE gets the data in the specified field and attempts to parse it as a `time.Time` object
and returns any errors that occur.
*/
func (r Record) TimeE(fieldName string, loc *time.Location) (time.Time, error) {
data := r.String(fieldName)
//Attempt to parse as timestamp in format MM/dd/yyyy HH:mm:ss
if match, err := regexp.MatchString(`^\d{2}\/\d{2}\/\d{4} \d{2}:\d{2}:\d{2}$`, data); err != nil {
return time.Time{}, err
} else if match {
return time.ParseInLocation("01/02/2006 15:04:05", data, loc)
}
//Attempt to parse as date in format MM/dd/yyyy
if match, err := regexp.MatchString(`^\d{2}\/\d{2}\/\d{4}$`, data); err != nil {
return time.Time{}, err
} else if match {
return time.ParseInLocation("01/02/2006", data, loc)
}
//Attempt to parse as timestamp in format yyyy-MM-dd HH:mm:ss
if match, err := regexp.MatchString(`^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$`, data); err != nil {
return time.Time{}, err
} else if match {
return time.ParseInLocation("2006-01-02 15:04:05", data, loc)
}
//Attempt to parse as date in format yyyy-MM-dd
if match, err := regexp.MatchString(`^\d{4}-\d{2}-\d{2}$`, data); err != nil {
return time.Time{}, err
} else if match {
return time.ParseInLocation("2006-01-02", data, loc)
}
return time.Time{}, ErrUnknownFormat
}
// Time gets the data in the specified field and attempts to parse it as a `time.Time` object.
func (r *Record) Time(fieldName string, loc *time.Location) time.Time {
t, _ := r.TimeE(fieldName, loc)
return t
}
/*
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
- int8
- int16
- int32
- int64
- float32
- float64
- bool
- time.Time (date and timestamp fields)
*/
func (r *Record) Map(obj interface{}, timeLoc *time.Location) {
v := reflect.ValueOf(obj).Elem()
//Loop through all struct fields
for i := 0; i < v.NumField(); i++ {
field := v.Field(i)
//Skip the field if it cannot be set
if !field.IsValid() || !field.CanSet() {
continue
}
//Get the `fm` tag of the field
tag := v.Type().Field(i).Tag.Get("fm")
//Set the struct field value depending on the underlying type
switch field.Interface().(type) {
case string:
field.SetString(r.String(tag))
case int, int8, int16, int32, int64:
field.SetInt(r.Int64(tag))
case float32, float64:
field.SetFloat(r.Float64(tag))
case bool:
field.SetBool(r.Bool(tag))
case time.Time:
field.Set(reflect.ValueOf(r.Time(tag, timeLoc)))
}
if field.Type() != reflect.TypeOf(Record{}) {
if field.Kind() == reflect.Struct {
//Map nested struct
r.Map(field.Addr().Interface(), timeLoc)
continue
} else if field.Kind() == reflect.Pointer && field.Elem().Kind() == reflect.Struct {
//Map nested pointer to struct
r.Map(field.Interface(), timeLoc)
continue
} else if field.Kind() == reflect.Pointer &&
field.Type().Elem() == reflect.TypeOf(time.Time{}) {
//Field is a time.Time pointer
t := r.Time(tag, timeLoc)
//Only set field if time is not zero
if field.IsNil() && !t.IsZero() {
//Nil pointer
field.Set(reflect.ValueOf(&t))
} else if !t.IsZero() {
//Value pointer
field.Elem().Set(reflect.ValueOf(t))
}
continue
}
}
}
}