from typing import Any, Dict, Iterable, List, Optional, Tuple from server.constants.delphi.skipping import SkippingRule def skip_item(items: List[Dict[str, Any]], index: int, item_skipping_rules: Iterable[SkippingRule]) -> bool: """Remove the whole item from items if needed based on the item_skipping_rules. Args: items: sequence to select item from. index: index of item to check. item_skipping_rules: rules to remove the whole item from the response. Returns: boolean flag for whether the item was removed. """ item = items[index] for rule in item_skipping_rules or []: if rule.key in item and item[rule.key] in rule.values: items.pop(index) return True return False def skip_nullable_data(item: Dict[str, Any], fields_skipping_rules: Iterable[SkippingRule]): """Remove nullable data from the item based on the fields_skipping_rules. Args: item: item to check. fields_skipping_rules: rules to remove particular fields from the response item. """ for rule in fields_skipping_rules or []: if rule.key in item and item[rule.key] in rule.values: del item[rule.key] def skip_extra_data( item: Dict[str, Any], filter_rules: Dict[str, Dict[str, Optional[Tuple[str]]]], extra_keys: Dict[str, Tuple[str]], dsp_key: str, ): """Remove redundant data from the item based on the filters and skipped_extra_keys rules. Args: item: item to check. filter_rules: map of filters by dsp and key name for extra keys in the result item. Each particular filter contains tuple of only fileds to be included in response for this key. extra_keys: map of extra (controlled by 'include') data keys in the result item by dsp. dsp_key: key for getting dsp value from the item. """ dsp = item.get(dsp_key) if not dsp: return filters = filter_rules.get(dsp, {}) skipped_extra_keys = set(extra_keys.get(dsp, [])) - set(filters.keys()) for key in skipped_extra_keys: if key in item: del item[key] for outer_key, filtered_inner_keys in filters.items(): if not filtered_inner_keys: continue original = item.get(outer_key, {}) item[outer_key] = {k: original.get(k) for k in filtered_inner_keys}