"""Event Handler.""" from content_utils.exceptions import InvalidMessageException from src import config from src.connectors import get_graphql_connector from src.connectors import get_os_connector from src.exceptions import ReviewQueueItemExplicitSkip def event_handler(msg_body): """Event handling.""" _validate_message(msg_body, ['operation']) _check_explicit_skip(msg_body) if msg_body['operation'] == 'update': update_in_index(msg_body) return 'Patched index' elif msg_body['operation'] == 'delete': delete_from_index(msg_body) return 'Removed from index' elif msg_body['operation'] == 'add': add_to_index(msg_body) return 'Added to index' raise InvalidMessageException(f'Unhandled operation: {msg_body["operation"]}') def _validate_message(msg_body, fields): for field in fields: if not msg_body.get(field): raise InvalidMessageException(f'missing "{field}" in message body') def _check_explicit_skip(msg_body): """Skip explicitly listed review queue items.""" review_queue_id = msg_body.get('review_queue_id') if review_queue_id in config.SKIP_REVIEW_QUEUE_ITEMS: raise ReviewQueueItemExplicitSkip( f'Explicit Skip: review_queue_id={review_queue_id}') def update_in_index(msg_body): """Update an indexed product.""" _validate_message(msg_body, ['product_id', 'review_queue_id']) product_info = get_graphql_connector().get_indexable_product({ 'product_id': msg_body['product_id'], 'review_queue_id': msg_body['review_queue_id'] }) get_os_connector().patch_product(product_info) def delete_from_index(msg_body): """Remove an indexed product.""" _validate_message(msg_body, ['product_id']) get_os_connector().remove_product(msg_body['product_id']) def add_to_index(msg_body): """Add an indexed product.""" _validate_message(msg_body, ['product_id', 'review_queue_id']) index_record = get_graphql_connector().get_indexable_product({ 'product_id': msg_body['product_id'], 'review_queue_id': msg_body['review_queue_id'] }) get_os_connector().index_product(index_record)