-
Notifications
You must be signed in to change notification settings - Fork 8
/
type.go
600 lines (518 loc) · 11.4 KB
/
type.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
package jsonapi
import (
"encoding/json"
"errors"
"fmt"
"reflect"
"sort"
"strconv"
"strings"
"time"
)
// Attribute types are the possible types for attributes.
//
// Those constants are numbers that represent the types. Each type has a string
// representation which should be used instead of the numbers when storing
// that information. The numbers can change between any version of this library,
// even if it potentially can break existing code.
//
// The names are as follow:
// - string
// - int, int8, int16, int32, int64
// - uint, uint8, uint16, uint32, uint64
// - bool
// - time (Go type is time.Time)
// - bytes (Go type is []uint8 or []byte)
//
// An asterisk is present as a prefix when the type is nullable (like *string).
//
// Developers are encouraged to use the constants, the Type struct, and other
// tools to handle attribute types instead of dealing with strings.
const (
AttrTypeInvalid = iota
AttrTypeString
AttrTypeInt
AttrTypeInt8
AttrTypeInt16
AttrTypeInt32
AttrTypeInt64
AttrTypeUint
AttrTypeUint8
AttrTypeUint16
AttrTypeUint32
AttrTypeUint64
AttrTypeBool
AttrTypeTime
AttrTypeBytes
)
// A Type stores all the necessary information about a type as represented in
// the JSON:API specification.
//
// NewFunc stores a function that returns a new Resource of the type defined by
// the object with all the fields and the ID set to their zero values. Users may
// call the New method which returns the result of NewFunc if it is non-nil,
// otherwise it returns a SoftResource based on the type.
//
// New makes sure NewFunc is not nil and then calls it, but does not use any
// kind of locking in the process. Therefore, it is unsafe to set NewFunc and
// call New concurrently.
type Type struct {
Name string
Attrs map[string]Attr
Rels map[string]Rel
NewFunc func() Resource
}
// AddAttr adds an attributes to the type.
func (t *Type) AddAttr(attr Attr) error {
// Validation
if attr.Name == "" {
return fmt.Errorf("jsonapi: attribute name is empty")
}
if GetAttrTypeString(attr.Type, attr.Nullable) == "" {
return fmt.Errorf("jsonapi: attribute type is invalid")
}
// Make sure the name isn't already used
for i := range t.Attrs {
if t.Attrs[i].Name == attr.Name {
return fmt.Errorf("jsonapi: attribute name %q is already used", attr.Name)
}
}
if t.Attrs == nil {
t.Attrs = map[string]Attr{}
}
t.Attrs[attr.Name] = attr
return nil
}
// RemoveAttr removes an attribute from the type if it exists.
func (t *Type) RemoveAttr(attr string) {
for i := range t.Attrs {
if t.Attrs[i].Name == attr {
delete(t.Attrs, attr)
}
}
}
// AddRel adds a relationship to the type.
func (t *Type) AddRel(rel Rel) error {
// Validation
if rel.FromName == "" {
return fmt.Errorf("jsonapi: relationship name is empty")
}
if rel.ToType == "" {
return fmt.Errorf("jsonapi: relationship type is empty")
}
// Make sure the name isn't already used
for i := range t.Rels {
if t.Rels[i].FromName == rel.FromName {
return fmt.Errorf("jsonapi: relationship name %q is already used", rel.FromName)
}
}
if t.Rels == nil {
t.Rels = map[string]Rel{}
}
t.Rels[rel.FromName] = rel
return nil
}
// RemoveRel removes a relationship from the type if it exists.
func (t *Type) RemoveRel(rel string) {
for i := range t.Rels {
if t.Rels[i].FromName == rel {
delete(t.Rels, rel)
}
}
}
// Fields returns a list of the names of all the fields (attributes and
// relationships) in the type.
func (t *Type) Fields() []string {
fields := make([]string, 0, len(t.Attrs)+len(t.Rels))
for i := range t.Attrs {
fields = append(fields, t.Attrs[i].Name)
}
for i := range t.Rels {
fields = append(fields, t.Rels[i].FromName)
}
sort.Strings(fields)
return fields
}
// New calls the NewFunc field and returns the result Resource object.
//
// If NewFunc is nil, it returns a *SoftResource with its Type field set to the
// value of the receiver.
func (t *Type) New() Resource {
if t.NewFunc != nil {
return t.NewFunc()
}
return &SoftResource{Type: t}
}
// Equal returns true if both types have the same name, attributes,
// relationships. NewFunc is ignored.
func (t Type) Equal(typ Type) bool {
t.NewFunc = nil
typ.NewFunc = nil
return reflect.DeepEqual(t, typ)
}
// Copy deeply copies the receiver and returns the result.
func (t Type) Copy() Type {
ctyp := Type{
Name: t.Name,
Attrs: map[string]Attr{},
Rels: map[string]Rel{},
}
for name, attr := range t.Attrs {
ctyp.Attrs[name] = attr
}
for name, rel := range t.Rels {
ctyp.Rels[name] = rel
}
ctyp.NewFunc = t.NewFunc
return ctyp
}
// Attr represents a resource attribute.
type Attr struct {
Name string
Type int
Nullable bool
}
// UnmarshalToType unmarshals the data into a value of the type represented by
// the attribute and returns it.
func (a Attr) UnmarshalToType(data []byte) (any, error) {
if a.Nullable && string(data) == "null" {
return GetZeroValue(a.Type, a.Nullable), nil
}
var (
v any
err error
)
switch a.Type {
case AttrTypeString:
var s string
err = json.Unmarshal(data, &s)
if a.Nullable {
v = &s
} else {
v = s
}
case AttrTypeInt:
v, err = strconv.Atoi(string(data))
if a.Nullable {
n := v.(int)
v = &n
} else {
v = v.(int)
}
case AttrTypeInt8:
v, err = strconv.Atoi(string(data))
if a.Nullable {
n := int8(v.(int))
v = &n
} else {
v = int8(v.(int))
}
case AttrTypeInt16:
v, err = strconv.Atoi(string(data))
if a.Nullable {
n := int16(v.(int))
v = &n
} else {
v = int16(v.(int))
}
case AttrTypeInt32:
v, err = strconv.Atoi(string(data))
if a.Nullable {
n := int32(v.(int))
v = &n
} else {
v = int32(v.(int))
}
case AttrTypeInt64:
v, err = strconv.Atoi(string(data))
if a.Nullable {
n := int64(v.(int))
v = &n
} else {
v = int64(v.(int))
}
case AttrTypeUint:
v, err = strconv.ParseUint(string(data), 10, 64)
if a.Nullable {
n := uint(v.(uint64))
v = &n
} else {
v = uint(v.(uint64))
}
case AttrTypeUint8:
v, err = strconv.ParseUint(string(data), 10, 8)
if a.Nullable {
n := uint8(v.(uint64))
v = &n
} else {
v = uint8(v.(uint64))
}
case AttrTypeUint16:
v, err = strconv.ParseUint(string(data), 10, 16)
if a.Nullable {
n := uint16(v.(uint64))
v = &n
} else {
v = uint16(v.(uint64))
}
case AttrTypeUint32:
v, err = strconv.ParseUint(string(data), 10, 32)
if a.Nullable {
n := uint32(v.(uint64))
v = &n
} else {
v = uint32(v.(uint64))
}
case AttrTypeUint64:
v, err = strconv.ParseUint(string(data), 10, 64)
if a.Nullable {
n := v.(uint64)
v = &n
} else {
v = v.(uint64)
}
case AttrTypeBool:
var b bool
if string(data) == "true" {
b = true
} else if string(data) != "false" {
err = errors.New("boolean is not true or false")
}
v = b
if a.Nullable {
v = &b
}
case AttrTypeTime:
var t time.Time
err = json.Unmarshal(data, &t)
v = t
if a.Nullable {
v = &t
}
case AttrTypeBytes:
s := make([]byte, len(data))
err := json.Unmarshal(data, &s)
if err != nil {
panic(err)
}
if a.Nullable {
v = &s
} else {
v = s
}
default:
err = errors.New("attribute is of invalid or unknown type")
}
if err != nil {
return nil, NewErrInvalidFieldValueInBody(
a.Name,
string(data),
GetAttrTypeString(a.Type, a.Nullable),
)
}
return v, nil
}
// Rel represents a resource relationship.
type Rel struct {
FromType string
FromName string
ToOne bool
ToType string
ToName string
FromOne bool
}
// Invert returns the inverse relationship of r.
func (r *Rel) Invert() Rel {
return Rel{
FromType: r.ToType,
FromName: r.ToName,
ToOne: r.FromOne,
ToType: r.FromType,
ToName: r.FromName,
FromOne: r.ToOne,
}
}
// Normalize inverts the relationship if necessary in order to have it in the
// right direction and returns the result.
//
// This is the form stored in Schema.Rels.
func (r *Rel) Normalize() Rel {
from := r.FromType + r.FromName
to := r.ToType + r.ToName
if from < to || r.ToName == "" {
return *r
}
return r.Invert()
}
// String builds and returns the name of the receiving Rel.
//
// r.Normalize is always called.
func (r Rel) String() string {
r = r.Normalize()
id := r.FromType + "_" + r.FromName
if r.ToName != "" {
id += "_" + r.ToType + "_" + r.ToName
}
return id
}
// GetAttrType returns the attribute type as an int (see constants) and a
// boolean that indicates whether the attribute can be null or not.
func GetAttrType(t string) (int, bool) {
nullable := strings.HasPrefix(t, "*")
if nullable {
t = t[1:]
}
switch t {
case "string":
return AttrTypeString, nullable
case "int":
return AttrTypeInt, nullable
case "int8":
return AttrTypeInt8, nullable
case "int16":
return AttrTypeInt16, nullable
case "int32":
return AttrTypeInt32, nullable
case "int64":
return AttrTypeInt64, nullable
case "uint":
return AttrTypeUint, nullable
case "uint8":
return AttrTypeUint8, nullable
case "uint16":
return AttrTypeUint16, nullable
case "uint32":
return AttrTypeUint32, nullable
case "uint64":
return AttrTypeUint64, nullable
case "bool":
return AttrTypeBool, nullable
case "time.Time", "time":
return AttrTypeTime, nullable
case "[]uint8", "[]byte", "bytes":
return AttrTypeBytes, nullable
default:
return AttrTypeInvalid, false
}
}
// GetAttrTypeString returns the name of the attribute type specified by t (see
// constants) and nullable.
func GetAttrTypeString(t int, nullable bool) string {
str := ""
switch t {
case AttrTypeString:
str = "string"
case AttrTypeInt:
str = "int"
case AttrTypeInt8:
str = "int8"
case AttrTypeInt16:
str = "int16"
case AttrTypeInt32:
str = "int32"
case AttrTypeInt64:
str = "int64"
case AttrTypeUint:
str = "uint"
case AttrTypeUint8:
str = "uint8"
case AttrTypeUint16:
str = "uint16"
case AttrTypeUint32:
str = "uint32"
case AttrTypeUint64:
str = "uint64"
case AttrTypeBool:
str = "bool"
case AttrTypeTime:
str = "time"
case AttrTypeBytes:
str = "bytes"
default:
str = ""
}
if nullable {
return "*" + str
}
return str
}
// GetZeroValue returns the zero value of the attribute type represented by the
// specified int (see constants).
//
// If nullable is true, the returned value is a nil pointer.
func GetZeroValue(t int, nullable bool) any {
switch t {
case AttrTypeString:
if nullable {
return (*string)(nil)
}
return ""
case AttrTypeInt:
if nullable {
return (*int)(nil)
}
return int(0)
case AttrTypeInt8:
if nullable {
return (*int8)(nil)
}
return int8(0)
case AttrTypeInt16:
if nullable {
return (*int16)(nil)
}
return int16(0)
case AttrTypeInt32:
if nullable {
return (*int32)(nil)
}
return int32(0)
case AttrTypeInt64:
if nullable {
return (*int64)(nil)
}
return int64(0)
case AttrTypeUint:
if nullable {
return (*uint)(nil)
}
return uint(0)
case AttrTypeUint8:
if nullable {
return (*uint8)(nil)
}
return uint8(0)
case AttrTypeUint16:
if nullable {
return (*uint16)(nil)
}
return uint16(0)
case AttrTypeUint32:
if nullable {
return (*uint32)(nil)
}
return uint32(0)
case AttrTypeUint64:
if nullable {
return (*uint64)(nil)
}
return uint64(0)
case AttrTypeBool:
if nullable {
return (*bool)(nil)
}
return false
case AttrTypeTime:
if nullable {
return (*time.Time)(nil)
}
return time.Time{}
case AttrTypeBytes:
if nullable {
return (*[]byte)(nil)
}
return []byte{}
default:
return nil
}
}