|
| 1 | +"""Validators for the search parameters of the Algolia endpoint.""" |
| 2 | + |
| 3 | +import re |
| 4 | + |
| 5 | +from django.core.exceptions import ValidationError |
| 6 | +from django.core.validators import validate_slug |
| 7 | + |
| 8 | + |
| 9 | +def validate_index_name(index_name): |
| 10 | + """Validate index name.""" |
| 11 | + if not index_name or not isinstance(index_name, str): |
| 12 | + message = "indexName is required and must be a string." |
| 13 | + raise ValidationError(message) |
| 14 | + |
| 15 | + try: |
| 16 | + validate_slug(index_name) |
| 17 | + except ValidationError: |
| 18 | + message = ( |
| 19 | + "Invalid indexName value provided. " |
| 20 | + "Only alphanumeric characters hyphens and underscores are allowed." |
| 21 | + ) |
| 22 | + raise ValidationError(message) from None |
| 23 | + |
| 24 | + |
| 25 | +def validate_limit(limit): |
| 26 | + """Validate limit.""" |
| 27 | + if not isinstance(limit, int): |
| 28 | + message = "hitsPerPage must be an integer." |
| 29 | + raise ValidationError(message) |
| 30 | + |
| 31 | + min_limit = 1 |
| 32 | + max_limit = 1000 |
| 33 | + if limit < min_limit or limit > max_limit: |
| 34 | + message = "hitsPerPage value must be between 1 and 1000." |
| 35 | + raise ValidationError(message) |
| 36 | + |
| 37 | + |
| 38 | +def validate_page(page): |
| 39 | + """Validate page.""" |
| 40 | + if not isinstance(page, int): |
| 41 | + message = "page value must be an integer." |
| 42 | + raise ValidationError(message) |
| 43 | + |
| 44 | + if page <= 0: |
| 45 | + message = "page value must be a positive integer." |
| 46 | + raise ValidationError(message) |
| 47 | + |
| 48 | + |
| 49 | +def validate_query(query): |
| 50 | + """Validate query.""" |
| 51 | + if not query: |
| 52 | + return |
| 53 | + |
| 54 | + if not isinstance(query, str): |
| 55 | + message = "query must be a string." |
| 56 | + raise ValidationError(message) |
| 57 | + |
| 58 | + if not re.match(r"^[a-zA-Z0-9-_ ]*$", query): |
| 59 | + message = ( |
| 60 | + "Invalid query value provided. " |
| 61 | + "Only alphanumeric characters, hyphens, spaces, and underscores are allowed." |
| 62 | + ) |
| 63 | + raise ValidationError(message) |
| 64 | + |
| 65 | + |
| 66 | +def validate_facet_filters(facet_filters): |
| 67 | + """Validate facet filters.""" |
| 68 | + if not isinstance(facet_filters, list): |
| 69 | + message = "facetFilters must be a list." |
| 70 | + raise ValidationError(message) |
| 71 | + |
| 72 | + |
| 73 | +def validate_search_params(data): |
| 74 | + """Validate search parameters.""" |
| 75 | + validate_facet_filters(data.get("facetFilters", [])) |
| 76 | + validate_index_name(data.get("indexName")) |
| 77 | + validate_limit(data.get("hitsPerPage", 25)) |
| 78 | + validate_page(data.get("page", 1)) |
| 79 | + validate_query(data.get("query", "")) |
0 commit comments