| Total Complexity | 7 | 
| Total Lines | 45 | 
| Duplicated Lines | 0 % | 
| Changes | 0 | ||
| 1 | """Custom validator for the Annif API."""  | 
            ||
| 2 | |||
| 3 | import logging  | 
            ||
| 4 | |||
| 5 | import jsonschema  | 
            ||
| 6 | from connexion import decorators  | 
            ||
| 7 | from connexion.exceptions import BadRequestProblem  | 
            ||
| 8 | from connexion.utils import is_null  | 
            ||
| 9 | |||
| 10 | logger = logging.getLogger("openapi.validation") | 
            ||
| 11 | |||
| 12 | |||
| 13 | class CustomRequestBodyValidator(decorators.validation.RequestBodyValidator):  | 
            ||
| 14 | """Custom request body validator that overrides the default error message for the  | 
            ||
| 15 | 'maxItems' validator for the 'documents' property."""  | 
            ||
| 16 | |||
| 17 | def __init__(self, *args, **kwargs):  | 
            ||
| 18 | super().__init__(*args, **kwargs)  | 
            ||
| 19 | |||
| 20 | def validate_schema(self, data, url):  | 
            ||
| 21 | """Validate the request body against the schema."""  | 
            ||
| 22 | |||
| 23 | if self.is_null_value_valid and is_null(data):  | 
            ||
| 24 | return None # noqa  | 
            ||
| 25 | |||
| 26 | try:  | 
            ||
| 27 | self.validator.validate(data)  | 
            ||
| 28 | except jsonschema.ValidationError as exception:  | 
            ||
| 29 | if exception.validator == "maxItems" and list(exception.schema_path) == [  | 
            ||
| 30 | "properties",  | 
            ||
| 31 | "documents",  | 
            ||
| 32 | "maxItems",  | 
            ||
| 33 | ]:  | 
            ||
| 34 | exception.message = "too many items"  | 
            ||
| 35 | |||
| 36 | error_path_msg = self._error_path_message(exception=exception)  | 
            ||
| 37 | logger.error(  | 
            ||
| 38 |                 "{url} validation error: {error}{error_path_msg}".format( | 
            ||
| 39 | url=url, error=exception.message, error_path_msg=error_path_msg  | 
            ||
| 40 | ),  | 
            ||
| 41 |                 extra={"validator": "body"}, | 
            ||
| 42 | )  | 
            ||
| 43 |             raise BadRequestProblem(detail=f"{exception.message}{error_path_msg}") | 
            ||
| 44 | return None  | 
            ||
| 45 |