Changeset View
Changeset View
Standalone View
Standalone View
swh/graphql/resolvers/scalars.py
# Copyright (C) 2022 The Software Heritage developers | # Copyright (C) 2022 The Software Heritage developers | ||||
# See the AUTHORS file at the top-level directory of this distribution | # See the AUTHORS file at the top-level directory of this distribution | ||||
# License: GNU General Public License version 3, or any later version | # License: GNU General Public License version 3, or any later version | ||||
# See top-level LICENSE file for more information | # See top-level LICENSE file for more information | ||||
from datetime import datetime | from datetime import datetime | ||||
from ariadne import ScalarType | from ariadne import ScalarType | ||||
from swh.graphql.errors import InvalidInputError | from swh.graphql.errors import InvalidInputError | ||||
from swh.graphql.utils import utils | from swh.graphql.utils import utils | ||||
from swh.model import hashutil | |||||
from swh.model.exceptions import ValidationError | from swh.model.exceptions import ValidationError | ||||
from swh.model.model import TimestampWithTimezone | from swh.model.model import TimestampWithTimezone | ||||
from swh.model.swhids import CoreSWHID | from swh.model.swhids import CoreSWHID | ||||
datetime_scalar = ScalarType("DateTime") | datetime_scalar = ScalarType("DateTime") | ||||
swhid_scalar = ScalarType("SWHID") | swhid_scalar = ScalarType("SWHID") | ||||
id_scalar = ScalarType("ID") | id_scalar = ScalarType("ID") | ||||
content_hash_scalar = ScalarType("ContentHash") | |||||
@id_scalar.serializer | @id_scalar.serializer | ||||
def serialize_id(value) -> str: | def serialize_id(value) -> str: | ||||
if type(value) is str: | if type(value) is str: | ||||
value = value.encode() | value = value.encode() | ||||
return value.hex() | return value.hex() | ||||
Show All 15 Lines | def validate_swhid(value): | ||||
except ValidationError as e: | except ValidationError as e: | ||||
raise InvalidInputError("Invalid SWHID", e) | raise InvalidInputError("Invalid SWHID", e) | ||||
return swhid | return swhid | ||||
@swhid_scalar.serializer | @swhid_scalar.serializer | ||||
def serialize_swhid(value): | def serialize_swhid(value): | ||||
return str(value) | return str(value) | ||||
@content_hash_scalar.value_parser | |||||
def validate_content_hash(value): | |||||
try: | |||||
hash_type, hash_string = value.split(":") | |||||
hash_value = hashutil.hash_to_bytes(hash_string) | |||||
except ValueError as e: | |||||
raise InvalidInputError("Invalid content hash", e) | |||||
if hash_type not in hashutil.ALGORITHMS: | |||||
raise InvalidInputError("Invalid hash algorithm") | |||||
return hash_type, hash_value |