...
1 package graphql
2
3 import (
4 "encoding/json"
5 "fmt"
6 "io"
7 "strconv"
8 )
9
10 func MarshalID(s string) Marshaler {
11 return MarshalString(s)
12 }
13
14 func UnmarshalID(v interface{}) (string, error) {
15 switch v := v.(type) {
16 case string:
17 return v, nil
18 case json.Number:
19 return string(v), nil
20 case int:
21 return strconv.Itoa(v), nil
22 case int64:
23 return strconv.FormatInt(v, 10), nil
24 case float64:
25 return fmt.Sprintf("%f", v), nil
26 case bool:
27 if v {
28 return "true", nil
29 } else {
30 return "false", nil
31 }
32 case nil:
33 return "null", nil
34 default:
35 return "", fmt.Errorf("%T is not a string", v)
36 }
37 }
38
39 func MarshalIntID(i int) Marshaler {
40 return WriterFunc(func(w io.Writer) {
41 writeQuotedString(w, strconv.Itoa(i))
42 })
43 }
44
45 func UnmarshalIntID(v interface{}) (int, error) {
46 switch v := v.(type) {
47 case string:
48 return strconv.Atoi(v)
49 case int:
50 return v, nil
51 case int64:
52 return int(v), nil
53 case json.Number:
54 return strconv.Atoi(string(v))
55 default:
56 return 0, fmt.Errorf("%T is not an int", v)
57 }
58 }
59
View as plain text