Skip to content

Commit ab19907

Browse files
authored
refactor: UnmarshalID implementation (#3093)
1 parent a9965fb commit ab19907

File tree

2 files changed

+76
-10
lines changed

2 files changed

+76
-10
lines changed

‎graphql/id.go‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,9 @@ func UnmarshalID(v any) (string, error) {
2222
case int64:
2323
return strconv.FormatInt(v, 10), nil
2424
case float64:
25-
return fmt.Sprintf("%f", v), nil
25+
return strconv.FormatFloat(v, 'f', 6, 64), nil
2626
case bool:
27-
if v {
28-
return "true", nil
29-
} else {
30-
return "false", nil
31-
}
27+
return strconv.FormatBool(v), nil
3228
case nil:
3329
return "null", nil
3430
default:

‎graphql/id_test.go‎

Lines changed: 74 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package graphql
22

33
import (
44
"bytes"
5+
"encoding/json"
56
"math"
67
"testing"
78

@@ -35,10 +36,19 @@ func TestUnmarshalID(t *testing.T) {
3536
ShouldError bool
3637
}{
3738
{
38-
Name: "int64",
39-
Input: int64(12),
40-
Expected: "12",
41-
ShouldError: false,
39+
Name: "string",
40+
Input: "str",
41+
Expected: "str",
42+
},
43+
{
44+
Name: "json.Number float64",
45+
Input: json.Number("1.2"),
46+
Expected: "1.2",
47+
},
48+
{
49+
Name: "int64",
50+
Input: int64(12),
51+
Expected: "12",
4252
},
4353
{
4454
Name: "int64 max",
@@ -50,6 +60,66 @@ func TestUnmarshalID(t *testing.T) {
5060
Input: math.MinInt64,
5161
Expected: "-9223372036854775808",
5262
},
63+
{
64+
Name: "bool true",
65+
Input: true,
66+
Expected: "true",
67+
},
68+
{
69+
Name: "bool false",
70+
Input: false,
71+
Expected: "false",
72+
},
73+
{
74+
Name: "nil",
75+
Input: nil,
76+
Expected: "null",
77+
},
78+
{
79+
Name: "float64",
80+
Input: 1.234567,
81+
Expected: "1.234567",
82+
},
83+
{
84+
Name: "float64 0",
85+
Input: 0.0,
86+
Expected: "0.000000",
87+
},
88+
{
89+
Name: "float64 loss of precision",
90+
Input: 0.0000005,
91+
Expected: "0.000000",
92+
},
93+
{
94+
Name: "float64 rounding up",
95+
Input: 0.0000006,
96+
Expected: "0.000001",
97+
},
98+
{
99+
Name: "float64 negative",
100+
Input: -1.234560,
101+
Expected: "-1.234560",
102+
},
103+
{
104+
Name: "float64 math.Inf(0)",
105+
Input: math.Inf(0),
106+
Expected: "+Inf",
107+
},
108+
{
109+
Name: "float64 math.Inf(-1)",
110+
Input: math.Inf(-1),
111+
Expected: "-Inf",
112+
},
113+
{
114+
Name: "float64 -math.Inf(0)",
115+
Input: -math.Inf(0),
116+
Expected: "-Inf",
117+
},
118+
{
119+
Name: "not a string",
120+
Input: struct{}{},
121+
ShouldError: true,
122+
},
53123
}
54124

55125
for _, tt := range tests {

0 commit comments

Comments
 (0)