Repository navigation
Expand file tree
/
Copy pathparse.go
More file actions
63 lines (58 loc) · 1.92 KB
/
Copy pathparse.go
File metadata and controls
63 lines (58 loc) · 1.92 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
package humus
import (
"fmt"
"reflect"
"github.com/Vliro/humus/parse"
jsoniter "github.com/json-iterator/go"
)
var json = jsoniter.Config{
EscapeHTML: true,
SortMapKeys: true,
ValidateJsonRawMessage: true,
//MaxDepth: -1,
TagKey: "predicate",
}.Froze()
//handleResponse takes the raw input from Dgraph and deserializes into the interfaces
//as provided by inp given the query names. It will use easyjson if available,
//otherwise defaults to standard json.
func handleResponse(res []byte, inp []interface{}, names []string) error {
i := -1
//This uses zero memory allocations to traverse the query tree.
//Since we do not want to deserialize the query root but rather the containing values
//traversing the query root with zero allocations is a large benefit, making jsonparser
//a very useful library here.
//Alternatively you can deserialize into an arbitrary object and use that but it is a lot less efficient.
return parse.ObjectEach(res, func(key []byte, value []byte, _ parse.ValueType, _ int) error {
i++
//Skip empty return values.
if string(value) == "[]" {
return nil
}
if string(key) != names[i] {
return fmt.Errorf("mismatch between query name and key: %s : %s", string(key), names[i])
}
return singleResponse(value, inp[i])
})
}
//singleResponse deserializes the json in value into the pointer value
//represented by inp.
func singleResponse(value []byte, inp interface{}) error {
if len(value) == 0 {
return nil
}
val := reflect.TypeOf(inp)
kind := val.Kind()
if !(kind == reflect.Ptr) {
return fmt.Errorf("parse: invalid non-assignable input to singleResponse, got type %s", val.String())
}
val = val.Elem()
kind = val.Kind()
isArray := kind == reflect.Slice || kind == reflect.Array
//No need for massive reflect to check if it is an array
if value[0] == '[' {
if !isArray {
value = value[1 : len(value)-1]
}
}
return json.Unmarshal(value, inp)
}