|
| 1 | +import logging |
| 2 | +from typing import Any, Callable, Dict |
| 3 | + |
| 4 | +from pydantic import BaseModel, ValidationError |
| 5 | + |
| 6 | +from aws_lambda_powertools.middleware_factory import lambda_handler_decorator |
| 7 | + |
| 8 | +from .envelopes.base import BaseEnvelope |
| 9 | + |
| 10 | +logger = logging.getLogger(__name__) |
| 11 | + |
| 12 | + |
| 13 | +@lambda_handler_decorator |
| 14 | +def validator( |
| 15 | + handler: Callable[[Dict, Any], Any], |
| 16 | + event: Dict[str, Any], |
| 17 | + context: Dict[str, Any], |
| 18 | + inbound_schema_model: BaseModel, |
| 19 | + outbound_schema_model: BaseModel, |
| 20 | + envelope: BaseEnvelope, |
| 21 | +) -> Any: |
| 22 | + """Decorator to create validation for lambda handlers events - both inbound and outbound |
| 23 | +
|
| 24 | + As Lambda follows (event, context) signature we can remove some of the boilerplate |
| 25 | + and also capture any exception any Lambda function throws or its response as metadata |
| 26 | +
|
| 27 | + Example |
| 28 | + ------- |
| 29 | + **Lambda function using validation decorator** |
| 30 | +
|
| 31 | + @validator(inbound=inbound_schema_model, outbound=outbound_schema_model) |
| 32 | + def handler(parsed_event_model, context): |
| 33 | + ... |
| 34 | +
|
| 35 | + Parameters |
| 36 | + ---------- |
| 37 | + todo add |
| 38 | +
|
| 39 | + Raises |
| 40 | + ------ |
| 41 | + err |
| 42 | + TypeError or pydantic.ValidationError or any exception raised by the lambda handler itself |
| 43 | + """ |
| 44 | + lambda_handler_name = handler.__name__ |
| 45 | + logger.debug("Validating inbound schema") |
| 46 | + parsed_event_model = envelope.parse(event, inbound_schema_model) |
| 47 | + try: |
| 48 | + logger.debug(f"Calling handler {lambda_handler_name}") |
| 49 | + response = handler({"orig": event, "custom": parsed_event_model}, context) |
| 50 | + logger.debug("Received lambda handler response successfully") |
| 51 | + logger.debug(response) |
| 52 | + except Exception: |
| 53 | + logger.exception(f"Exception received from {lambda_handler_name}") |
| 54 | + raise |
| 55 | + |
| 56 | + try: |
| 57 | + logger.debug("Validating outbound response schema") |
| 58 | + outbound_schema_model(**response) |
| 59 | + except (ValidationError, TypeError): |
| 60 | + logger.exception(f"Validation exception received from {lambda_handler_name} response event") |
| 61 | + raise |
| 62 | + return response |
0 commit comments