"""This module holds the logic for doing simple data conversions.""" import stringcase def node_to_dict(node): """Unpack the data from a node.""" data = {k: v for k, v in node.items()} return data def format_response(payload): """Format payload according to conventions.""" if type(payload) is list: payload = {'items': payload, 'pagination': {'total_records': len(payload)}} return to_snake(payload) def to_snake(data): """Transform the keys of the payload to snake case. Args: data (dict): the payload to format the keys. Returns: dict: a new dictionary with the formatted payload """ snake_case_dict = {} for k, v in data.items(): snake_case_dict[stringcase.snakecase(k)] = v return snake_case_dict def to_camel(data): """Transform the keys of the payload to camel case. Args: data (dict): the payload to format the keys. Returns: dict: a new dictionary with the formatted payload """ camel_case_dict = {} for k, v in data.items(): camel_case_dict[stringcase.camelcase(k)] = v return camel_case_dict def to_int(data): """Try to transform data into int (handle bothe uuid and Int for node id). Args: data: String/Int Returns: data: Int or String """ try: return int(data) except Exception: return str(data) def escape_term(term): """Apply escaping to the passed in query term. Args: term: String Returns: String with escaped characters """ escape_rules = [ '+', '-', '&&', '/', '||', '!', '(', ')', '{', '}', '[', ']', '^', '~', '*', '?', ':', '"', ] # noqa escaped_term = term.replace('\\', r'\\') for rule in escape_rules: escaped_term = escaped_term.replace(rule, fr'\{rule}') return escaped_term