"""Request helper methods.""" from flask import request from marshmallow import ValidationError from royalties.constants.constants import DEFAULT_PAGE_LIMIT, DEFAULT_PAGE_OFFSET from royalties.constants.error import ( ERROR_INVALID_LIMIT_OFFSET, ERROR_POST_REQUEST_DUPLICATE_RECORDS, ) def validate_pagination_params( limit: int = DEFAULT_PAGE_LIMIT, offset: int = DEFAULT_PAGE_OFFSET ) -> dict: """Format and validate pagination parameters.""" try: limit = int(limit) offset = int(offset) except ValueError: raise ValidationError(ERROR_INVALID_LIMIT_OFFSET) pagination_params = { 'limit': max(limit, 1), 'offset': max(offset, DEFAULT_PAGE_OFFSET), } return pagination_params def get_optional_numeric_list_from_params(): """Get data from request params and validate them.""" optional_params = request.json if not optional_params: return return [int(param) for param in optional_params] def validate_post_request_contains_unique_data(request_body: list): """Validate if post request body contains unique records. Args: request_body (list): a POST request body """ list_of_unique_records = list() for record in request_body: if record in list_of_unique_records: raise ValidationError(ERROR_POST_REQUEST_DUPLICATE_RECORDS.format(record)) else: list_of_unique_records.append(record) return True