Skip to content

Commit

Permalink
Add UintID type binding (#2980)
Browse files Browse the repository at this point in the history
  • Loading branch information
nawivee authored Mar 25, 2024
1 parent d192a59 commit 780bf27
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ models:
model:
- github.com/99designs/gqlgen/graphql.IntID # a go integer
- github.com/99designs/gqlgen/graphql.ID # or a go string
- github.com/99designs/gqlgen/graphql.UintID # or a go uint
```

This means gqlgen will be able to automatically bind to strings or ints for models you have written yourself, but the
Expand Down
29 changes: 29 additions & 0 deletions graphql/id.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,32 @@ func UnmarshalIntID(v interface{}) (int, error) {
return 0, fmt.Errorf("%T is not an int", v)
}
}

func MarshalUintID(i uint) Marshaler {
return WriterFunc(func(w io.Writer) {
writeQuotedString(w, strconv.FormatUint(uint64(i), 10))
})
}

func UnmarshalUintID(v interface{}) (uint, error) {
switch v := v.(type) {
case string:
result, err := strconv.ParseUint(v, 10, 64)
return uint(result), err
case int:
return uint(v), nil
case int64:
return uint(v), nil
case int32:
return uint(v), nil
case uint32:
return uint(v), nil
case uint64:
return uint(v), nil
case json.Number:
result, err := strconv.ParseUint(string(v), 10, 64)
return uint(result), err
default:
return 0, fmt.Errorf("%T is not an uint", v)
}
}
35 changes: 35 additions & 0 deletions graphql/id_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,38 @@ func TestUnmarshalID(t *testing.T) {
})
}
}

func TestMarshalUintID(t *testing.T) {
assert.Equal(t, `"12"`, m2s(MarshalUintID(12)))
}

func TestUnMarshalUintID(t *testing.T) {

result, err := UnmarshalUintID("12")
assert.Equal(t, uint(12), result)
assert.NoError(t, err)

result, err = UnmarshalUintID(12)
assert.Equal(t, uint(12), result)
assert.NoError(t, err)

result, err = UnmarshalUintID(int64(12))
assert.Equal(t, uint(12), result)
assert.NoError(t, err)

result, err = UnmarshalUintID(int32(12))
assert.Equal(t, uint(12), result)
assert.NoError(t, err)

result, err = UnmarshalUintID(int(12))
assert.Equal(t, uint(12), result)
assert.NoError(t, err)

result, err = UnmarshalUintID(uint32(12))
assert.Equal(t, uint(12), result)
assert.NoError(t, err)

result, err = UnmarshalUintID(uint64(12))
assert.Equal(t, uint(12), result)
assert.NoError(t, err)
}

0 comments on commit 780bf27

Please sign in to comment.