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