"""Schemas for get__conflicts endpoints.""" import marshmallow from conflict_manager.constants import error as error_consts from conflict_manager.constants import query_parameters as query_consts class PaginationSchema(marshmallow.Schema): """Validation schema for query parameters of get_conflicts endpoints.""" class Meta: """Schema options.""" unknown = marshmallow.EXCLUDE def __init__(self, *args, **kwargs): """Constructor. Args: sort_by_options (list): Optional list of sort options. default_sort_by (str): Option default column to sort_by. """ self.sort_by_options = kwargs.pop('sort_by_options', []) self.default_sort_by = kwargs.pop('default_sort_by', None) super().__init__(*args, **kwargs) sort_by = marshmallow.fields.String( load_default=None, required=False) sort_order = marshmallow.fields.String( load_default=query_consts.DEFAULT_SORT_ORDER, validate=marshmallow.validate.OneOf( query_consts.ALLOWED_SORT_ORDER, error=error_consts.INVALID_SORT_ORDER_MSG)) offset = marshmallow.fields.Integer( data_key=query_consts.PAGE_OFFSET, load_default=query_consts.DEFAULT_OFFSET, validate=marshmallow.validate.Range( min=0, error=error_consts.INVALID_PAGE_OFFSET_MSG)) limit = marshmallow.fields.Integer( data_key=query_consts.PAGE_LIMIT, load_default=query_consts.DEFAULT_LIMIT, validate=marshmallow.validate.Range( min=0, error=error_consts.INVALID_PAGE_LIMIT_MSG)) @marshmallow.validates(query_consts.SORT_BY) def validate_sort_by(self, value, **kwargs): """Validate sort_by parameter. Args: value (str): Value to validate. Can also be None. Raises: ValidationError """ if value is None or value == '': value = self.default_sort_by if value is not None and value not in self.sort_by_options: raise marshmallow.ValidationError( error_consts.INVALID_SORT_BY_MSG.format( input=value, choices=', '.join(self.sort_by_options))) @marshmallow.post_load def finalize_output(self, data, **kwargs): """Finalize output. Args: data (dict): Deserialized dict Return: dict """ if self.default_sort_by and not data[query_consts.SORT_BY]: data[query_consts.SORT_BY] = self.default_sort_by return data