diff --git a/task_module.py b/task_module.py new file mode 100644 index 0000000..0000001 --- /dev/null +++ b/task_module.py @@ -0,0 +1,31 @@ +from graphene import Scalar +from graphql.error import GraphQLError +from graphql.language import StringValueNode + +class HexScalar(Scalar): + """ + The `Hex` scalar type represents a hexadecimal-encoded String. + """ + + @staticmethod + def serialize(value): + if isinstance(value, bytes): + return value.hex() + else: + value = str(value).encode("utf-8") + return value.hex() + + @classmethod + def parse(cls, value): + try: + return bytes.fromhex(value) + except ValueError as e: + raise GraphQLError(f"Invalid hex string: {value}") + + @classmethod + def parse_literal(cls, node, _variables=None): + if not isinstance(node, StringValueNode): + raise GraphQLError( + f"Hex cannot represent non-string value" + ) + return cls.parse(node.value) \ No newline at end of file