Use custom type for big int in graphql
Signed-off-by: Sacha Al Himdani <sacha@getprobo.com>
This commit is contained in:
60
pkg/server/graphql/types/bigint/bigint.go
Normal file
60
pkg/server/graphql/types/bigint/bigint.go
Normal file
@@ -0,0 +1,60 @@
|
||||
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
// PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
package bigint
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"strconv"
|
||||
|
||||
"github.com/99designs/gqlgen/graphql"
|
||||
)
|
||||
|
||||
type BigIntScalar = int64
|
||||
|
||||
func MarshalBigIntScalar(i int64) graphql.Marshaler {
|
||||
return graphql.WriterFunc(func(w io.Writer) {
|
||||
w.Write([]byte(strconv.FormatInt(i, 10)))
|
||||
})
|
||||
}
|
||||
|
||||
func UnmarshalBigIntScalar(v any) (int64, error) {
|
||||
switch val := v.(type) {
|
||||
case string:
|
||||
i, err := strconv.ParseInt(val, 10, 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("invalid BigInt value: %v", err)
|
||||
}
|
||||
return i, nil
|
||||
case int:
|
||||
return int64(val), nil
|
||||
case int32:
|
||||
return int64(val), nil
|
||||
case int64:
|
||||
return val, nil
|
||||
case float32:
|
||||
if val != float32(int64(val)) {
|
||||
return 0, fmt.Errorf("BigInt cannot represent non-integer value: %v", val)
|
||||
}
|
||||
return int64(val), nil
|
||||
case float64:
|
||||
if val != float64(int64(val)) {
|
||||
return 0, fmt.Errorf("BigInt cannot represent non-integer value: %v", val)
|
||||
}
|
||||
return int64(val), nil
|
||||
default:
|
||||
return 0, fmt.Errorf("cannot unmarshal %T into BigInt", v)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user