"""Schemas for filtering on 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 FilterSchema(marshmallow.Schema): """Validation schema for filter parameters of get_conflicts endpoints.""" class Meta: """Schema options.""" unknown = marshmallow.EXCLUDE def __init__(self, *args, **kwargs): """Constructor. Args: filter_fields (list): Optional list of eligible filter fields. """ self.filter_fields = kwargs.pop('filter_fields', []) super().__init__(*args, **kwargs) query = marshmallow.fields.String(load_default=None, required=False) fields = marshmallow.fields.List( marshmallow.fields.String(), load_default=None, required=False) @marshmallow.validates(query_consts.FILTER_FIELDS) def validate_fields(self, value, **kwargs): """Validate filter fields parameter. Args: value (str): Value to validate. Can also be None. Raises: ValidationError """ if value is None or value == '': value = None for val in value: if val is not None and val not in self.filter_fields: raise marshmallow.ValidationError( error_consts.INVALID_FILTER_FIELD_MSG.format(value)) @marshmallow.post_load def finalize_output(self, data, **kwargs): """Finalize output. Args: data (dict): Deserialized dict Return: dict """ if self.filter_fields and not data[query_consts.FILTER_FIELDS]: data[query_consts.FILTER_FIELDS] = [] return data