-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmarshal.go
418 lines (340 loc) · 11 KB
/
marshal.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
package jsonapi
import (
"encoding/json"
"errors"
"fmt"
"reflect"
"strings"
)
// RelationshipType specifies the type of a relationship.
type RelationshipType int
// The available relationship types.
//
// Note: DefaultRelationship guesses the relationship type based on the
// pluralization of the reference name.
const (
DefaultRelationship RelationshipType = iota
ToOneRelationship
ToManyRelationship
)
// The MarshalIdentifier interface is necessary to give an element a unique ID.
//
// Note: The implementation of this interface is mandatory.
type MarshalIdentifier interface {
GetID() string
}
// ReferenceID contains all necessary information in order to reference another
// struct in JSON API.
type ReferenceID struct {
ID string
Type string
Name string
Relationship RelationshipType
}
// A Reference information about possible references of a struct.
//
// Note: If IsNotLoaded is set to true, the `data` field will be omitted and only
// the `links` object will be generated. You should do this if there are some
// references, but you do not want to load them. Otherwise, if IsNotLoaded is
// false and GetReferencedIDs() returns no IDs for this reference name, an
// empty `data` field will be added which means that there are no references.
type Reference struct {
Type string
Name string
IsNotLoaded bool
Relationship RelationshipType
}
// The MarshalReferences interface must be implemented if the struct to be
// serialized has relationships.
type MarshalReferences interface {
GetReferences() []Reference
}
// The MarshalLinkedRelations interface must be implemented if there are
// reference ids that should be included in the document.
type MarshalLinkedRelations interface {
MarshalReferences
MarshalIdentifier
GetReferencedIDs() []ReferenceID
}
// The MarshalIncludedRelations interface must be implemented if referenced
// structs should be included in the document.
type MarshalIncludedRelations interface {
MarshalReferences
MarshalIdentifier
GetReferencedStructs() []MarshalIdentifier
}
// A ServerInformation implementor can be passed to MarshalWithURLs to generate
// the `self` and `related` urls inside `links`.
type ServerInformation interface {
GetBaseURL() string
GetPrefix() string
}
// MarshalWithURLs can be used to pass along a ServerInformation implementor.
func MarshalWithURLs(data interface{}, information ServerInformation) ([]byte, error) {
document, err := MarshalToStruct(data, information, nil)
if err != nil {
return nil, err
}
return json.Marshal(document)
}
// Marshal wraps data in a Document and returns its JSON encoding.
//
// Data can be a struct, a pointer to a struct or a slice of structs. All structs
// must at least implement the `MarshalIdentifier` interface.
func Marshal(data interface{}) ([]byte, error) {
document, err := MarshalToStruct(data, nil, nil)
if err != nil {
return nil, err
}
return json.Marshal(document)
}
func MarshalOnlyFields(data interface{}, fields FilterFields) ([]byte, error) {
document, err := MarshalToStruct(data, nil, fields)
if err != nil {
return nil, err
}
return json.Marshal(document)
}
// MarshalToStruct marshals an api2go compatible struct into a jsonapi Document
// structure which then can be marshaled to JSON. You only need this method if
// you want to extract or extend parts of the document. You should directly use
// Marshal to get a []byte with JSON in it.
func MarshalToStruct(data interface{}, information ServerInformation, fields FilterFields) (*Document, error) {
if data == nil {
return &Document{}, nil
}
switch reflect.TypeOf(data).Kind() {
case reflect.Slice:
return marshalSlice(data, information, fields)
case reflect.Struct, reflect.Ptr:
return marshalStruct(data.(MarshalIdentifier), information, fields)
default:
return nil, errors.New("Marshal only accepts slice, struct or ptr types")
}
}
func marshalSlice(data interface{}, information ServerInformation, fields FilterFields) (*Document, error) {
result := &Document{}
val := reflect.ValueOf(data)
dataElements := make([]Data, val.Len())
var referencedStructs []MarshalIdentifier
for i := 0; i < val.Len(); i++ {
k := val.Index(i).Interface()
element, ok := k.(MarshalIdentifier)
if !ok {
return nil, errors.New("all elements within the slice must implement api2go.MarshalIdentifier")
}
err := marshalData(element, &dataElements[i], information, fields)
if err != nil {
return nil, err
}
included, ok := k.(MarshalIncludedRelations)
if ok {
referencedStructs = append(referencedStructs, included.GetReferencedStructs()...)
}
}
includedElements, err := filterDuplicates(referencedStructs, information, fields)
if err != nil {
return nil, err
}
result.Data = &DataContainer{
DataArray: dataElements,
}
if includedElements != nil && len(includedElements) > 0 {
result.Included = includedElements
}
return result, nil
}
func filterDuplicates(input []MarshalIdentifier, information ServerInformation, fields FilterFields) ([]Data, error) {
alreadyIncluded := map[string]map[string]bool{}
includedElements := []Data{}
for _, referencedStruct := range input {
structType := getStructType(referencedStruct)
if alreadyIncluded[structType] == nil {
alreadyIncluded[structType] = make(map[string]bool)
}
if !alreadyIncluded[structType][referencedStruct.GetID()] {
var data Data
err := marshalData(referencedStruct, &data, information, fields)
if err != nil {
return nil, err
}
includedElements = append(includedElements, data)
alreadyIncluded[structType][referencedStruct.GetID()] = true
}
}
return includedElements, nil
}
func marshalData(element MarshalIdentifier, data *Data, information ServerInformation, fields FilterFields) error {
refValue := reflect.ValueOf(element)
if refValue.Kind() == reflect.Ptr && refValue.IsNil() {
return errors.New("MarshalIdentifier must not be nil")
}
var attributes []byte
var err error
data.Type = getStructType(element)
if len(fields[data.Type]) > 0 {
co := CustomObject{
Fields: fields[data.Type],
Object: element,
}
attributes, err = json.Marshal(co)
if err != nil {
return err
}
} else {
attributes, err = json.Marshal(element)
if err != nil {
return err
}
}
data.Attributes = attributes
data.ID = element.GetID()
if references, ok := element.(MarshalLinkedRelations); ok {
data.Relationships = getStructRelationships(references, information)
}
return nil
}
func GetInterfaceValueByFieldName(n interface{}, field_name string) (interface{}, bool) {
s := reflect.ValueOf(n)
if s.Kind() == reflect.Ptr {
s = s.Elem()
}
if s.Kind() != reflect.Struct {
return nil, false
}
f := s.FieldByName(field_name)
if !f.IsValid() {
return nil, false
}
return f.Interface(), true
}
func isToMany(relationshipType RelationshipType, name string) bool {
if relationshipType == DefaultRelationship {
return Pluralize(name) == name
}
return relationshipType == ToManyRelationship
}
func getStructRelationships(relationer MarshalLinkedRelations, information ServerInformation) map[string]Relationship {
referencedIDs := relationer.GetReferencedIDs()
sortedResults := map[string][]ReferenceID{}
relationships := map[string]Relationship{}
for _, referenceID := range referencedIDs {
sortedResults[referenceID.Name] = append(sortedResults[referenceID.Name], referenceID)
}
references := relationer.GetReferences()
// helper map to check if all references are included to also include empty ones
notIncludedReferences := map[string]Reference{}
for _, reference := range references {
notIncludedReferences[reference.Name] = reference
}
for name, referenceIDs := range sortedResults {
relationships[name] = Relationship{}
// if referenceType is plural, we need to use an array for data, otherwise it's just an object
container := RelationshipDataContainer{}
if isToMany(referenceIDs[0].Relationship, referenceIDs[0].Name) {
// multiple elements in links
container.DataArray = []RelationshipData{}
for _, referenceID := range referenceIDs {
container.DataArray = append(container.DataArray, RelationshipData{
Type: referenceID.Type,
ID: referenceID.ID,
})
}
} else {
container.DataObject = &RelationshipData{
Type: referenceIDs[0].Type,
ID: referenceIDs[0].ID,
}
}
// set URLs if necessary
links := getLinksForServerInformation(relationer, name, information)
relationship := Relationship{
Data: &container,
Links: links,
}
relationships[name] = relationship
// this marks the reference as already included
delete(notIncludedReferences, referenceIDs[0].Name)
}
// check for empty references
for name, reference := range notIncludedReferences {
container := RelationshipDataContainer{}
// Plural empty relationships need an empty array and empty to-one need a null in the json
if !reference.IsNotLoaded && isToMany(reference.Relationship, reference.Name) {
container.DataArray = []RelationshipData{}
}
links := getLinksForServerInformation(relationer, name, information)
relationship := Relationship{
Links: links,
}
// skip relationship data completely if IsNotLoaded is set
if !reference.IsNotLoaded {
relationship.Data = &container
}
relationships[name] = relationship
}
return relationships
}
func getLinksForServerInformation(relationer MarshalLinkedRelations, name string, information ServerInformation) *Links {
if information == nil {
return nil
}
links := &Links{}
prefix := strings.Trim(information.GetBaseURL(), "/")
namespace := strings.Trim(information.GetPrefix(), "/")
structType := getStructType(relationer)
if namespace != "" {
prefix += "/" + namespace
}
links.Self = fmt.Sprintf("%s/%s/%s/relationships/%s", prefix, structType, relationer.GetID(), name)
links.Related = fmt.Sprintf("%s/%s/%s/%s", prefix, structType, relationer.GetID(), name)
return links
}
func marshalStruct(data MarshalIdentifier, information ServerInformation, fields FilterFields) (*Document, error) {
var contentData Data
err := marshalData(data, &contentData, information, fields)
if err != nil {
return nil, err
}
result := &Document{
Data: &DataContainer{
DataObject: &contentData,
},
}
included, ok := data.(MarshalIncludedRelations)
if ok {
included, err := filterDuplicates(included.GetReferencedStructs(), information, fields)
if err != nil {
return nil, err
}
if len(included) > 0 {
result.Included = included
}
}
return result, nil
}
func getStructType(data interface{}) string {
entityName, ok := data.(EntityNamer)
if ok {
return entityName.GetName()
}
reflectType := reflect.TypeOf(data)
if reflectType.Kind() == reflect.Ptr {
return Pluralize(Jsonify(reflectType.Elem().Name()))
}
return Pluralize(Jsonify(reflectType.Name()))
}
func getType(data interface{}) reflect.Type {
reflectType := reflect.TypeOf(data)
if reflectType.Kind() == reflect.Ptr {
return reflectType.Elem()
}
return reflectType
}
func getValue(data interface{}) reflect.Value {
reflectValue := reflect.ValueOf(data)
if reflectValue.Kind() == reflect.Ptr {
return reflectValue.Elem()
}
return reflectValue
}