Skip to content

add BigInt type #1261

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Aug 28, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions graphene/types/scalars.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,33 @@ def parse_literal(ast):
return num


class BigInt(Scalar):
"""
The `BigInt` scalar type represents non-fractional whole numeric values.
`BigInt` is not constrained to 32-bit like the `Int` type and thus is a less
compatible type.
"""

@staticmethod
def coerce_int(value):
try:
num = int(value)
except ValueError:
try:
num = int(float(value))
except ValueError:
return None
return num

serialize = coerce_int
parse_value = coerce_int

@staticmethod
def parse_literal(ast):
if isinstance(ast, IntValueNode):
return int(ast.value)


class Float(Scalar):
"""
The `Float` scalar type represents signed double-precision fractional
Expand Down
22 changes: 21 additions & 1 deletion graphene/types/tests/test_scalar.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from ..scalars import Scalar
from ..scalars import Scalar, Int, BigInt
from graphql.language.ast import IntValueNode


def test_scalar():
Expand All @@ -7,3 +8,22 @@ class JSONScalar(Scalar):

assert JSONScalar._meta.name == "JSONScalar"
assert JSONScalar._meta.description == "Documentation"


def test_ints():
assert Int.parse_value(2 ** 31 - 1) is not None
assert Int.parse_value("2.0") is not None
assert Int.parse_value(2 ** 31) is None

assert Int.parse_literal(IntValueNode(value=str(2 ** 31 - 1))) == 2 ** 31 - 1
assert Int.parse_literal(IntValueNode(value=str(2 ** 31))) is None

assert Int.parse_value(-(2 ** 31)) is not None
assert Int.parse_value(-(2 ** 31) - 1) is None

assert BigInt.parse_value(2 ** 31) is not None
assert BigInt.parse_value("2.0") is not None
assert BigInt.parse_value(-(2 ** 31) - 1) is not None

assert BigInt.parse_literal(IntValueNode(value=str(2 ** 31 - 1))) == 2 ** 31 - 1
assert BigInt.parse_literal(IntValueNode(value=str(2 ** 31))) == 2 ** 31