-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathjsonapi.go
More file actions
1308 lines (1128 loc) · 33.4 KB
/
Copy pathjsonapi.go
File metadata and controls
1308 lines (1128 loc) · 33.4 KB
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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package jsonapi marshals and unmarshals JSON:API v1.1 formatted JSON.
// The mapping between JSON:API values and Go values is defined with
// struct tags, which can be overridden with custom marshalling and unmarshaling
// functions.
package jsonapi
import (
"cmp"
"encoding/json"
"errors"
"fmt"
"sync"
"unsafe"
"reflect"
"slices"
"strings"
)
const (
// tag keys
tagKeyJson = "json"
tagKeyJsonApi = "jsonapi"
// tag values
tagValueIgnore = "-"
tagValueId = "id"
tagValueAttr = "attr"
tagValueRel = "rel"
tagValueMeta = "meta"
tagValueLink = "link"
// options
tagValueOmitEmpty = "omitempty"
tagValueString = "string"
)
var nullJson = json.RawMessage([]byte("null"))
// A TagError describes an unknown or incorrectly formatted
// jsonapi struct tag.
type TagError struct {
Field string
Err error
}
func (e *TagError) Error() string {
return "tag error on field '" + e.Field + "': " + e.Err.Error()
}
// An UnmarshalError describes an error returned by the underlying
// JSON unmarshaling library.
type UnmarshalError struct {
Field string
Err error
}
func (e *UnmarshalError) Error() string {
return "unmarshal error on field '" + e.Field + "': " + e.Err.Error()
}
// A MarshalError describes an error returned by the underlying
// JSON marshaling library.
type MarshalError struct {
Field string
Err error
}
func (e *MarshalError) Error() string {
return "marshal error on field '" + e.Field + "': " + e.Err.Error()
}
// A FieldTypeError describes a Go struct field of a type that
// cannot be marshaled to, or unmarshaled from, JSON:API.
type FieldTypeError struct {
Field string
Kind reflect.Kind
}
func (e *FieldTypeError) Error() string {
return "unsupported type on field '" + e.Field + "': " + e.Kind.String()
}
// A ResourceTypeError describes a Go type that cannot be be marshaled to,
// or unmarshaled from, a JSON:API [resource] (ie, not a struct, or does not
// implement [ResourceMarshaler] or [ResourceUnmarshaler]).
//
// [resource]: https://jsonapi.org/format/#document-resource-objects
type ResourceTypeError struct {
Type reflect.Type
}
func (e *ResourceTypeError) Error() string {
if e.Type != nil {
return "unsupported resource type: " + e.Type.Name()
}
return "unsupported resource type: nil"
}
// An IllegalUnmarshalError describes an illegal input to [UnmarshalResource]
// (ie, not a pointer, or nil).
type IllegalUnmarshalError struct {
Value reflect.Value
}
func (e *IllegalUnmarshalError) Error() string {
if e.Value.IsValid() {
return "non-pointer: " + e.Value.Type().Name()
}
return "nil"
}
// A SelfReferentialPointerError describes a loop of pointers.
type SelfReferentialPointerError struct {
Value reflect.Value
}
func (e *SelfReferentialPointerError) Error() string {
return "self-referential pointer: " + e.Value.String()
}
// ResourceUnmarshaler is the interface implemented by types that
// can unmarshal themselves from JSON:API-formatted JSON.
type ResourceUnmarshaler interface {
UnmarshalJsonApiResource([]byte) error
}
// ResourceMarshaler is the interface implemented by types that
// can marshal themselves into JSON:API-formatted JSON.
type ResourceMarshaler interface {
MarshalJsonApiResource() ([]byte, error)
}
var (
resourceMarshalerType = reflect.TypeFor[ResourceMarshaler]()
resourceUnmarshalerType = reflect.TypeFor[ResourceUnmarshaler]()
)
type resourceIdentifier struct {
Type string `json:"type,omitempty"`
Id json.RawMessage `json:"id,omitempty"`
}
type toOneRelationship struct {
Data resourceIdentifier `json:"data,omitempty"`
Links map[string]json.RawMessage `json:"links,omitempty"`
Meta map[string]json.RawMessage `json:"meta,omitempty"`
}
type toManyRelationship struct {
Data []resourceIdentifier `json:"data,omitempty"`
Links map[string]json.RawMessage `json:"links,omitempty"`
Meta map[string]json.RawMessage `json:"meta,omitempty"`
}
type resource struct {
resourceIdentifier
Attributes map[string]json.RawMessage
ToOneRelationships map[string]*toOneRelationship
ToManyRelationships map[string]*toManyRelationship
Links map[string]json.RawMessage
Meta map[string]json.RawMessage
}
func newResource() resource {
return resource{
resourceIdentifier: resourceIdentifier{},
Attributes: map[string]json.RawMessage{},
ToOneRelationships: map[string]*toOneRelationship{},
ToManyRelationships: map[string]*toManyRelationship{},
Meta: map[string]json.RawMessage{},
Links: map[string]json.RawMessage{},
}
}
func (r *resource) MarshalJSON() ([]byte, error) {
type alias struct {
resourceIdentifier
Attributes map[string]json.RawMessage `json:"attributes,omitempty"`
Relationships map[string]any `json:"relationships,omitempty"`
Links map[string]json.RawMessage `json:"links,omitempty"`
Meta map[string]json.RawMessage `json:"meta,omitempty"`
}
a := alias{
resourceIdentifier: r.resourceIdentifier,
Attributes: r.Attributes,
Links: r.Links,
Meta: r.Meta,
}
if len(r.ToOneRelationships)+len(r.ToManyRelationships) > 0 {
a.Relationships = make(map[string]any, len(r.ToOneRelationships)+len(r.ToManyRelationships))
for k, v := range r.ToOneRelationships {
a.Relationships[k] = v
}
for k, v := range r.ToManyRelationships {
a.Relationships[k] = v
}
}
return json.Marshal(a)
}
func (r *resource) UnmarshalJSON(data []byte) error {
type relAlias struct {
Meta map[string]json.RawMessage `json:"meta"`
Data json.RawMessage `json:"data"`
Links map[string]json.RawMessage `json:"links"`
}
type alias struct {
resourceIdentifier
Attributes map[string]json.RawMessage `json:"attributes"`
Relationships map[string]relAlias `json:"relationships"`
Links map[string]json.RawMessage `json:"links"`
Meta map[string]json.RawMessage `json:"meta"`
}
a := alias{}
if err := json.Unmarshal(data, &a); err != nil {
return err
}
r.resourceIdentifier = a.resourceIdentifier
r.Attributes = a.Attributes
r.Links = a.Links
r.Meta = a.Meta
r.ToOneRelationships = map[string]*toOneRelationship{}
r.ToManyRelationships = map[string]*toManyRelationship{}
for name, rel := range a.Relationships {
switch rel.Data[0] {
case '[':
ids := []resourceIdentifier{}
if err := json.Unmarshal(rel.Data, &ids); err != nil {
return err
}
r.ToManyRelationships[name] = &toManyRelationship{
Meta: rel.Meta,
Data: ids,
Links: rel.Links,
}
case '{':
id := resourceIdentifier{}
if err := json.Unmarshal(rel.Data, &id); err != nil {
return err
}
r.ToOneRelationships[name] = &toOneRelationship{
Meta: rel.Meta,
Data: id,
Links: rel.Links,
}
default:
return fmt.Errorf("cannot unmarshal into relationship data")
}
}
return nil
}
// MashalResource returns the JSON:API encoding of [resource] a.
//
// If a is nil or not a valid Resource type (ie is neither a struct nor a [ResourceMarshaler])
// then a [ResourceTypeError] is returned.
//
// If a implements [ResourceMarshaler], then its [ResourceMarshaler.MarshalJsonApiResource]
// function is called.
//
// Otherwise, the encoding of each of a's struct fields is defined by the the "jsonapi" key
// in the field's tag. The following formats are accepted:
//
// - "id,<type-name>[,<opt1>[,<opt2>]]": field is encoded as the resource type and id.
// - "attr[,<name>[,<opt1>[,opt2]]]": field is be encoded as an attribute.
// - "rel,<name>,<type-name>[,<opt1>[,<opt2>]]": field is encoded as a related resource id.
// - "link[,<name>[,<opt1>[,opt2]]]": field is encoded as a link.
// - "meta[,<name>[,<opt1>[,opt2]]]": field is encoded as a metadata item.
// - "-": field is ignored.
//
// The tag's first element specifies the field's destination in the
// resource, and must be either "id", "attr", "rel", "meta", "link" or "-".
// The "id" specification must be followed by a type,
// a "rel" specification must be followed by a name and type,
// and the "attr", "meta" and "link" specifications may be followed by a name.
// A field with no tag defaults to attr, and an empty or unspecified name will default to the field name.
//
// The following options are supported:
//
// - "omitempty" specifies that the field should be omitted
// from the Resource if the field has an empty value, as in the encoding/json
// package.
//
// - "string" signals that a floating point, integer, or boolean
// type should be encoded as a string. This is useful for using int or UUID
// fields as resource IDs.
//
// Some struct tag examples:
//
// // Field appears as the `id` field, converted to a string.
// // Additionally, a `type` field will be added with value `my-type`.
// Field int `jsonapi:"id,my-type,string"`
//
// // Field appears as an attribute with name `my-name`.
// Field int `jsonapi:"attr,my-name,omitempty"`
//
// // Field appears as an attribute with name `my-name`.
// Field int `json:"my-name"`
//
// // Field is excluded from the resource entirely:
// Field int `jsonapi:"-"`
//
// // Field appears as the "id" of a to-one relationship, with name `my-name`, and type `my-type`.
// Field int `jsonapi:"attr,my-name,my-type,string"`
//
// // Field elements appear as the "id" fields of a to-many relationship, with name `my-name`, and type `my-type`.
// Field []int `jsonapi:"attr,my-name,my-type,string"`
//
// // Field appears as an meta item with name `my-name`.
// Field int `jsonapi:"meta,my-name"`
//
// // Field appears as a link with name `my-name`.
// Field int `jsonapi:"link,my-name"`
//
// Embedded struct fields without a jsonapi tag are marshaled as if their inner exported fields
// were fields in the outer struct, subject to the same visibility rules defined in
// the `encoding/json` package.
// Embedded struct fields with a tag are treated as though they are not embedded.
//
// [resource]: https://jsonapi.org/format/#document-resource-objects
func MarshalResource(a any, opts ...marshalResourceOpt) ([]byte, error) {
marshalOpts := marshalResourceOpts{}
for _, opt := range opts {
if opt == nil {
return nil, fmt.Errorf("nil option")
}
marshalOpts = opt(marshalOpts)
}
v, err := derefInput(reflect.ValueOf(a), resourceMarshalerType)
if err != nil {
return nil, err
}
if v.Type().Implements(resourceMarshalerType) {
return v.Interface().(ResourceMarshaler).MarshalJsonApiResource()
}
r, err := format(a, v, marshalOpts)
if err != nil {
return nil, fmt.Errorf("jsonapi: %w", err)
}
data, err := json.Marshal(&r)
if err != nil {
return nil, fmt.Errorf("jsonapi: marshaling resource: %w", err)
}
return data, nil
}
func format(a any, v reflect.Value, opts marshalResourceOpts) (resource, error) {
fields, err := parseTags(v)
if err != nil {
return resource{}, fmt.Errorf("parsing tags: %w", err)
}
r := newResource()
for _, f := range fields {
if err := marshalField(v, &r, f); err != nil {
return resource{}, fmt.Errorf("marshaling field "+f.tag.name+": %w", err)
}
}
if err := applyMarshalOpts(a, r, opts); err != nil {
return resource{}, err
}
return r, nil
}
func marshalField(v reflect.Value, r *resource, f field) error {
if f.tag.typ == tagValueRel {
return marshalRel(v, r, f)
}
if f.tag.typ == tagValueId {
r.Type = f.tag.rscType
}
v, err := fieldByIndex(v, f.idxs)
if err != nil {
return err
}
v, err = derefValue(v)
if err != nil {
return err
}
if f.tag.omitempty && isEmpty(v) {
return nil
}
j, err := marshalJson(v, f.tag.quote)
if err != nil {
return &MarshalError{f.tag.name, err}
}
switch f.tag.typ {
case tagValueId:
r.resourceIdentifier.Id = j
case tagValueAttr:
r.Attributes[f.tag.name] = j
case tagValueMeta:
r.Meta[f.tag.name] = j
case tagValueLink:
r.Links[f.tag.name] = j
default:
return errors.New("unknown tag type " + f.tag.typ)
}
return nil
}
// UnmarshalResource parses the JSON:API-formatted [resource] data and stores
// the result in the value pointed to by a.
// If a is nil or not a pointer, an [IllegalUnmarshalError] is returned.
// If a does not point to a struct type or a [ResourceUnmarshaler], a
// [ResourceTypeError] is returned.
//
// If a implements [ResourceUnmarshaler], then its [ResourceUnmarshaler.UnmarshalJsonApiResource]
// function is called.
//
// Otherwise, a's struct fields are decoded using struct tag and embedding rules
// equivalent to those used by [MarshalResource].
//
// [resource]: https://jsonapi.org/format/#document-resource-objects
func UnmarshalResource(data []byte, a any) error {
v, err := derefUnmarshalInput(a)
if err != nil {
return fmt.Errorf("jsonapi: dereferencing input: %w", err)
}
if v.Type().Implements(resourceUnmarshalerType) {
return v.Interface().(ResourceUnmarshaler).UnmarshalJsonApiResource(data)
}
r := newResource()
if err := json.Unmarshal(data, &r); err != nil {
return fmt.Errorf("jsonapi: unmarshaling resource: %w", err)
}
return deformat(v, r)
}
func derefUnmarshalInput(a any) (reflect.Value, error) {
v := reflect.ValueOf(a)
if !v.IsValid() || v.Kind() != reflect.Pointer {
return reflect.Value{}, &IllegalUnmarshalError{Value: v}
}
return derefInput(v, resourceUnmarshalerType)
}
func deformat(v reflect.Value, r resource) error {
fields, err := parseTags(v)
if err != nil {
return fmt.Errorf("jsonapi: parsing tags: %w", err)
}
for _, f := range fields {
if err := unmarshalField(v, &r, f); err != nil {
return fmt.Errorf("jsonapi: unmarshaling field '"+f.tag.name+"': %w", err)
}
}
return nil
}
func unmarshalField(v reflect.Value, r *resource, f field) error {
if f.tag.typ == tagValueRel {
return unmarshalRel(v, r, f)
}
var j json.RawMessage
switch f.tag.typ {
case tagValueId:
j = r.resourceIdentifier.Id
case tagValueAttr:
j = r.Attributes[f.tag.name]
case tagValueMeta:
j = r.Meta[f.tag.name]
case tagValueLink:
j = r.Links[f.tag.name]
default:
return errors.New("unknown tag type " + f.tag.typ)
}
if len(j) == 0 {
return nil
}
v, err := initFieldByIndex(v, f.idxs)
if err != nil {
return err
}
if err := unmarshalJson(j, v, f.tag.quote); err != nil {
return &UnmarshalError{f.tag.name, err}
}
return nil
}
var enableFieldCache = true
var fieldCache sync.Map // map[reflect.Type][]field
// parseTags retrieves all attributes, relationships,
// etc from the input value.
// - performs a breadth-first search over the value
// rooted at v
// - if a struct field is found with no value, the
// search continues over the type tree rooted at
// f's type
// - modelled on the equivalent function in the
// encoding/json package to reduce heap allocs
// (see issue #1)
func parseTags(v reflect.Value) ([]field, error) {
if fields, ok := fieldCache.Load(v.Type()); ok {
return fields.([]field), nil
}
// every element in the queue represents a
// struct, either a type or a value
type structElem struct {
t reflect.Type
v reflect.Value
ok bool // true if the value is present
idxs []int // path to this structElem
}
var fields []field
types := map[reflect.Type]bool{}
next := []structElem{{t: v.Type(), v: v, ok: true}}
var current []structElem
// nb no allocations happen until needed
nextCount := map[reflect.Type]int{}
cache := true
for len(next) > 0 {
current, next = next, current[:0]
clear(nextCount)
// count struct fields
nfs := 0
for _, c := range current {
nfs += c.t.NumField()
}
// pre-allocate space in one go
fields = slices.Grow(fields, nfs) // alloc
next = slices.Grow(next, nfs) // alloc
for _, c := range current {
types[c.t] = true
for i := range c.t.NumField() {
f := c.t.Field(i) // alloc (!)
if !f.IsExported() && !f.Anonymous {
continue
}
typ, opts, ok := splitTypeAndOpts(f)
if typ == tagValueIgnore {
continue
}
fIdxs := make([]int, len(c.idxs)+1) // alloc
copy(fIdxs, c.idxs)
fIdxs[len(fIdxs)-1] = i
if !ok {
if f.Anonymous {
ft := derefType(f.Type)
if ft.Kind() == reflect.Struct {
if !types[ft] && nextCount[ft] < 2 {
nextCount[ft] = nextCount[ft] + 1
if c.ok {
fv, err := derefValue(c.v.Field(i))
if err != nil {
return nil, err
}
if fv.Kind() == reflect.Struct {
next = append(next, structElem{ft, fv, true, fIdxs}) // alloc
}
} else {
next = append(next, structElem{ft, reflect.Value{}, false, fIdxs}) // alloc
}
}
}
if ft.Kind() == reflect.Interface {
cache = false
if c.ok {
fv, err := derefValue(c.v.Field(i))
if err != nil {
return nil, err
}
if fv.Kind() == reflect.Struct {
fvt := fv.Type()
if !types[fvt] && nextCount[fvt] < 2 {
next = append(next, structElem{fvt, fv, true, fIdxs}) // alloc
nextCount[fvt] = nextCount[fvt] + 1
}
}
}
}
continue
}
typ = tagValueAttr
}
tag, err := parseTag(f, typ, opts)
if err != nil {
return nil, err
}
fld := field{
tag: tag,
idxs: fIdxs,
}
fields = append(fields, fld)
}
}
}
// sort by type, then name, then depth, then name precedence
slices.SortFunc(fields, func(a, b field) int {
if c := cmp.Compare(a.tag.typ, b.tag.typ); c != 0 {
return c
}
if c := cmp.Compare(a.tag.name, b.tag.name); c != 0 {
return c
}
if c := cmp.Compare(len(a.idxs), len(b.idxs)); c != 0 {
return c
}
return -cmp.Compare(a.tag.namePrec, b.tag.namePrec)
})
// now filter all fields that are overridden by those
// with a higher precedence
nFiltered := 0
for nType, i := 0, 0; i < len(fields); i += nType {
// find subslice of all fields of the same type
typ := fields[i].tag.typ
for nType = 1; i+nType < len(fields); nType++ {
if fields[i+nType].tag.typ != typ {
break
}
}
for nName, j := 0, i; j < i+nType; j += nName {
// find subslice of all fields with the same name (and type)
name := fields[j].tag.name
for nName = 1; j+nName < i+nType; nName++ {
if fields[j+nName].tag.name != name {
break
}
}
// if there are multiple with the same name and type,
// get the dominant field
field, ok := getDominantField(fields[j : j+nName])
if ok {
// copy back into original slice to save allocs
fields[nFiltered] = field
nFiltered++
}
}
}
fields = fields[:nFiltered]
if enableFieldCache && cache {
fieldCache.Store(v.Type(), fields) // 4 allocs
}
return fields, nil
}
// getDominantField returns the highest precedence
// field from the supplied list, with (zero, false)
// indicating a that no dominant tag can be determined.
// Assumes that the input list items all have the same name and
// type, and are sorted by depth then name precedence
func getDominantField(fs []field) (field, bool) {
if len(fs) == 0 {
return field{}, false
}
if len(fs) == 1 {
return fs[0], true
}
// if the two first items have the same depth and name prec then
// no dominant item can be determined
if len(fs[0].idxs) == len(fs[1].idxs) && fs[0].tag.namePrec == fs[1].tag.namePrec {
return field{}, false
}
// the first item must take precedence
return fs[0], true
}
func parseTag(f reflect.StructField, typ, opts string) (tag, error) {
k := derefType(f.Type).Kind()
switch k {
case reflect.Func, reflect.Chan, reflect.Complex64, reflect.Complex128:
return tag{}, &FieldTypeError{Field: f.Name, Kind: k}
}
switch typ {
case tagValueId:
return parseIdTag(f, opts)
case tagValueAttr:
return parseAttrTag(f, opts)
case tagValueMeta:
return parseMetaTag(f, opts)
case tagValueRel:
return parseRelTag(f, opts)
case tagValueLink:
return parseLinkTag(f, opts)
default:
return tag{}, &TagError{f.Name, errors.New("unknown tag type: " + typ)}
}
}
// field represents a tagged struct field,
// with tag representing the annotated tag, and idxs
// uniquely identifying this field with its path
// from the top-level struct
type field struct {
// the tag information annotated onto this struct field
tag tag
// idxs represents this and all ancestor fields' indexes
// within their parent structs
idxs []int
}
// tag represents a jsonapi struct tag
type tag struct {
// The jsonapi tag type, eg attribute, relationship etc
typ string
// The name that will appear in the output JSON.
name string
// The precedence of the name, with a jsonapi tag
// name being the highest, then a json tag, then
// the declared field name
namePrec int
// If this type is relationship or id, this field
// defines the resource type
rscType string
// whether the "string" flag was specified
quote bool
// whether the "omitempty" flag was specified
omitempty bool
}
// parseIdTag parses an id tag, eg `jsonapi:"id,name,type,opt1,opt2..."`
func parseIdTag(f reflect.StructField, opts string) (tag, error) {
rscType, opts := splitFirstAndOpts(opts)
if rscType == "" {
return tag{}, &TagError{f.Name, fmt.Errorf("required: type")}
}
omitempty, quote := optFlags(opts)
return tag{
typ: tagValueId,
rscType: rscType,
omitempty: omitempty,
quote: quote,
}, nil
}
// parseAttrTag parses an attribute tag, eg `jsonapi:"attr,name,opt1,opt2..."`
func parseAttrTag(f reflect.StructField, opts string) (tag, error) {
name, namePrec, opts := splitNameAndOpts(f, opts)
omitempty, quote := optFlags(opts)
return tag{
typ: tagValueAttr,
name: name,
namePrec: namePrec,
omitempty: omitempty,
quote: quote,
}, nil
}
// parseRelTag parses a relationship tag, eg `jsonapi:"rel,name,type,opt1,opt2..."`
func parseRelTag(f reflect.StructField, opts string) (tag, error) {
name, namePrec, opts := splitNameAndOpts(f, opts)
rscType, opts := splitFirstAndOpts(opts)
if rscType == "" {
return tag{}, &TagError{f.Name, fmt.Errorf("required: type")}
}
omitempty, quote := optFlags(opts)
return tag{
typ: tagValueRel,
name: name,
namePrec: namePrec,
rscType: rscType,
omitempty: omitempty,
quote: quote,
}, nil
}
func marshalRel(v reflect.Value, r *resource, f field) error {
v, err := fieldByIndex(v, f.idxs)
if err != nil {
return err
}
v, err = derefValue(v)
if err != nil {
return err
}
if f.tag.omitempty && isEmpty(v) {
return nil
}
if isToOne(v) {
return marshalToOneRel(v, r, f)
}
return marshalToManyRel(v, r, f)
}
func marshalToOneRel(v reflect.Value, r *resource, f field) error {
j, err := marshalJson(v, f.tag.quote)
if err != nil {
return &MarshalError{f.tag.name, err}
}
r.ToOneRelationships[f.tag.name] = &toOneRelationship{
Data: resourceIdentifier{
Type: f.tag.rscType,
Id: j,
},
}
return nil
}
func marshalToManyRel(v reflect.Value, r *resource, f field) error {
r.ToManyRelationships[f.tag.name] = &toManyRelationship{
Data: make([]resourceIdentifier, v.Len()),
}
for i := range v.Len() {
vi, err := derefValue(v.Index(i))
if err != nil {
return err
}
j, err := marshalJson(vi, f.tag.quote)
if err != nil {
return &MarshalError{f.tag.name, err}
}
r.ToManyRelationships[f.tag.name].Data[i] = resourceIdentifier{
Type: f.tag.rscType,
Id: j,
}
}
return nil
}
func unmarshalRel(v reflect.Value, r *resource, f field) error {
fv, err := fieldByIndex(v, f.idxs)
if err != nil {
return err
}
if isToOne(fv) {
return unmarshalToOneRel(v, r, f)
}
return unmarshalToManyRel(v, r, f)
}
func unmarshalToOneRel(v reflect.Value, r *resource, f field) error {
rel, ok := r.ToOneRelationships[f.tag.name]
if !ok {
return nil
}
if len(rel.Data.Id) == 0 {
return nil
}
v, err := initFieldByIndex(v, f.idxs)
if err != nil {
return err
}
if err := unmarshalJson(rel.Data.Id, v, f.tag.quote); err != nil {
return &UnmarshalError{f.tag.name, err}
}
return nil
}
func unmarshalToManyRel(v reflect.Value, r *resource, f field) error {
rels, ok := r.ToManyRelationships[f.tag.name]
if !ok {
return nil
}
if len(rels.Data) == 0 {
return nil
}
v, err := initFieldByIndex(v, f.idxs)
if err != nil {
return err
}
v.Grow(len(rels.Data) - v.Cap())
v.SetLen(len(rels.Data))
for i, rel := range rels.Data {
elem := v.Index(i)
initValue(elem)
if err := unmarshalJson(rel.Id, elem, f.tag.quote); err != nil {
return &UnmarshalError{f.tag.name, err}
}
}
return nil
}
// isToOne returns whether the supplied value represents a to-one or
// to-many relationship. A to-many relationship must be an array or slice
// of anything that is not a byte.
func isToOne(fv reflect.Value) bool {
return (fv.Kind() != reflect.Array && fv.Kind() != reflect.Slice) || fv.Type().Elem().Kind() == reflect.Uint8
}
// parseMetaTag parses a meta tag, eg `jsonapi:"meta,name,opt1,opt2..."`
func parseMetaTag(f reflect.StructField, opts string) (tag, error) {
name, namePrec, opts := splitNameAndOpts(f, opts)
omitempty, quote := optFlags(opts)
return tag{
typ: tagValueMeta,
name: name,
namePrec: namePrec,
omitempty: omitempty,
quote: quote,
}, nil
}
// parseMetaTag parses a link tag, eg `jsonapi:"link,name,opt1,opt2..."`
func parseLinkTag(f reflect.StructField, opts string) (tag, error) {
name, namePrec, opts := splitNameAndOpts(f, opts)
omitempty, quote := optFlags(opts)
return tag{
typ: tagValueLink,
name: name,
namePrec: namePrec,
omitempty: omitempty,
quote: quote,
}, nil
}
// splitTypeAndOpts extracts the jsonapi tag value from the supplied tag
// and returns the type string and all remaining options. The bool represents
// whether a tag was found.
// Eg `jsonapi:"attr,name,omitempty"` returns ("attribute", "name,omitempty", true )
func splitTypeAndOpts(f reflect.StructField) (string, string, bool) {
value, ok := f.Tag.Lookup(tagKeyJsonApi)
if !ok {
return "", "", false
}
typ, opts, _ := strings.Cut(value, ",")
return typ, opts, true