/
json_number.go
44 lines (38 loc) · 1.19 KB
/
json_number.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
/* _ _
*__ _____ __ ___ ___ __ _| |_ ___
*\ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
* \ V V / __/ (_| |\ V /| | (_| | || __/
* \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
*
* Copyright © 2016 - 2019 Weaviate. All rights reserved.
* LICENSE: https://github.com/creativesoftwarefdn/weaviate/blob/develop/LICENSE.md
* DESIGN & CONCEPT: Bob van Luijt (@bobvanluijt)
* CONTACT: hello@creativesoftwarefdn.org
*/package common
import (
"encoding/json"
"fmt"
"github.com/graphql-go/graphql"
)
// JSONNumberResolver turns json.Number types into number types usable by graphQL
func JSONNumberResolver(p graphql.ResolveParams) (interface{}, error) {
sourceMap, ok := p.Source.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("source is not a map, but %t", p.Source)
}
field, ok := sourceMap[p.Info.FieldName]
if !ok {
return nil, fmt.Errorf("sourcemap has no field '%s', got %#v", p.Info.FieldName, sourceMap)
}
switch n := field.(type) {
case json.Number:
return n.Float64()
case int64:
return float64(n), nil
case int:
return float64(n), nil
case float64:
return n, nil
}
return nil, fmt.Errorf("unknown number type for %t", field)
}