eafe84ef31
Adds MarshalUint64, UnmarshalUint64, and Uint64Marshaler for gqlgen- compatible uint64 string scalars without a gqlgen dependency. Co-authored-by: Cursor <cursoragent@cursor.com>
56 lines
1.3 KiB
Go
56 lines
1.3 KiB
Go
package dbx
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"strconv"
|
|
)
|
|
|
|
// Uint64Marshaler wraps a uint64 for GraphQL JSON output as a string scalar.
|
|
type Uint64Marshaler uint64
|
|
|
|
// MarshalGQL writes the uint64 as a JSON string for gqlgen compatibility.
|
|
func (u Uint64Marshaler) MarshalGQL(w io.Writer) {
|
|
fmt.Fprintf(w, "\"%d\"", uint64(u))
|
|
}
|
|
|
|
// MarshalUint64 marshals a uint64 as a JSON string to avoid JavaScript
|
|
// precision loss for integers larger than 2^53-1.
|
|
func MarshalUint64(i uint64) Uint64Marshaler {
|
|
return Uint64Marshaler(i)
|
|
}
|
|
|
|
// UnmarshalUint64 unmarshals a uint64 from a JSON string or number.
|
|
func UnmarshalUint64(v any) (uint64, error) {
|
|
switch value := v.(type) {
|
|
case string:
|
|
if value == "" {
|
|
return 0, nil
|
|
}
|
|
n, err := strconv.ParseUint(value, 10, 64)
|
|
if err != nil {
|
|
return 0, fmt.Errorf("invalid uint64 string: %w", err)
|
|
}
|
|
return n, nil
|
|
case int:
|
|
if value < 0 {
|
|
return 0, fmt.Errorf("invalid negative uint64: %d", value)
|
|
}
|
|
return uint64(value), nil
|
|
case int64:
|
|
if value < 0 {
|
|
return 0, fmt.Errorf("invalid negative uint64: %d", value)
|
|
}
|
|
return uint64(value), nil
|
|
case float64:
|
|
if value < 0 || value != float64(uint64(value)) {
|
|
return 0, fmt.Errorf("invalid uint64 number: %v", value)
|
|
}
|
|
return uint64(value), nil
|
|
case uint64:
|
|
return value, nil
|
|
default:
|
|
return 0, fmt.Errorf("invalid uint64 type: %T", v)
|
|
}
|
|
}
|