|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from typing import Union |
| 4 | + |
| 5 | +import orjson |
| 6 | + |
| 7 | +import fastjsonschema |
| 8 | + |
| 9 | +from aws_schema_registry.schema import DataFormat, Schema, ValidationError |
| 10 | + |
| 11 | + |
| 12 | +class JsonSchema(Schema): |
| 13 | + """Implementation of the `Schema` protocol for JSON schemas. |
| 14 | +
|
| 15 | + Arguments: |
| 16 | + definition: the schema, either as a parsed dict or a string |
| 17 | + """ |
| 18 | + |
| 19 | + def __init__(self, definition: Union[str, dict]): |
| 20 | + if isinstance(definition, str): |
| 21 | + self._dict = orjson.loads(definition) |
| 22 | + else: |
| 23 | + self._dict = definition |
| 24 | + self._compiled_validation_method = fastjsonschema.compile(self._dict) |
| 25 | + |
| 26 | + def __hash__(self): |
| 27 | + return hash(str(self)) |
| 28 | + |
| 29 | + def __eq__(self, other): |
| 30 | + return isinstance(other, JsonSchema) and \ |
| 31 | + self._dict == other._dict |
| 32 | + |
| 33 | + def __str__(self): |
| 34 | + return orjson.dumps(self._dict).decode() |
| 35 | + |
| 36 | + def __repr__(self): |
| 37 | + return '<JsonSchema %s>' % self._dict |
| 38 | + |
| 39 | + @property |
| 40 | + def data_format(self) -> DataFormat: |
| 41 | + return 'JSON' |
| 42 | + |
| 43 | + @property |
| 44 | + def fqn(self) -> str: |
| 45 | + return "" |
| 46 | + |
| 47 | + def read(self, bytes_: bytes): |
| 48 | + return orjson.loads(bytes_) |
| 49 | + |
| 50 | + def write(self, data) -> bytes: |
| 51 | + return orjson.dumps(data) |
| 52 | + |
| 53 | + def validate(self, data): |
| 54 | + try: |
| 55 | + self._compiled_validation_method(data) |
| 56 | + except fastjsonschema.exceptions.JsonSchemaValueException as e: |
| 57 | + raise ValidationError(str(e)) from e |
0 commit comments