-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprocessing.go
108 lines (86 loc) · 2.46 KB
/
processing.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
package wotlib
import (
"encoding/json"
"io/ioutil"
"net/http"
"github.com/piprate/json-gold/ld"
)
// Default json-ld options
var (
DefaultJSONDLDOptions = ld.NewJsonLdOptions("")
)
// FromResponse tries to extract an expanded wot td from a
// response object
func FromResponse(resp *http.Response) (ExpandedThingDescription, error) {
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return ExpandedThingDescription{}, err
}
return FromBytes(bytes)
}
// FromBytes expands input bytes and converts it to ExpandedThingDescription
func FromBytes(b []byte) (ExpandedThingDescription, error) {
proc := ld.NewJsonLdProcessor()
// lib is expecting a map
var asMap map[string]interface{}
err := json.Unmarshal(b, &asMap)
if err != nil {
return ExpandedThingDescription{}, err
}
expandedObj, err := proc.Expand(asMap, DefaultJSONDLDOptions)
if err != nil {
return ExpandedThingDescription{}, err
}
// first we need to convert the map into a byte arr again
expandedBytes, err := json.Marshal(expandedObj)
if err != nil {
return ExpandedThingDescription{}, err
}
// now we can properly convert it to a td
var td []ExpandedThingDescription
err = json.Unmarshal(expandedBytes, &td)
if err != nil {
return ExpandedThingDescription{}, err
}
return td[0], nil
}
// Compact compacts the thing description
func (e *ExpandedThingDescription) Compact() (json.RawMessage, error) {
compactedBytes, err := compact(e)
if err != nil {
return nil, err
}
return json.RawMessage(compactedBytes), nil
}
// Compact compacts an expanded property affordance
func (e *ExpandedPropertyAffordance) Compact() (json.RawMessage, error) {
compactedBytes, err := compact(e)
if err != nil {
return nil, err
}
return json.RawMessage(compactedBytes), nil
}
// Compact compacts an expanded action affordance
func (e *ExpandedActionAffordance) Compact() (json.RawMessage, error) {
compactedBytes, err := compact(e)
if err != nil {
return nil, err
}
return json.RawMessage(compactedBytes), nil
}
func compact(e interface{}) ([]byte, error) {
proc := ld.NewJsonLdProcessor()
expandedBytes, err := json.Marshal(e)
if err != nil {
return nil, err
}
var expandedMap map[string]interface{}
if err := json.Unmarshal(expandedBytes, &expandedMap); err != nil {
return nil, err
}
compactedMap, err := proc.Compact(expandedMap, map[string]interface{}{"@context": DefaultContext}, DefaultJSONDLDOptions)
if err != nil {
return nil, err
}
return json.Marshal(compactedMap)
}