Skip to content

feat(event-sources): cache parsed json in data class #909

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Dec 21, 2021
10 changes: 9 additions & 1 deletion aws_lambda_powertools/utilities/data_classes/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ def get_header_value(


class BaseProxyEvent(DictWrapper):
def __init__(self, data: Dict[str, Any]):
super().__init__(data)
self._parsed_json_body: Optional[Any] = None

@property
def headers(self) -> Dict[str, str]:
return self["headers"]
Expand All @@ -65,7 +69,11 @@ def body(self) -> Optional[str]:
@property
def json_body(self) -> Any:
"""Parses the submitted body as json"""
return json.loads(self.decoded_body)
if self._parsed_json_body:
return self._parsed_json_body

self._parsed_json_body = json.loads(self.decoded_body)
return self._parsed_json_body

@property
def decoded_body(self) -> str:
Expand Down
4 changes: 3 additions & 1 deletion tests/functional/test_data_classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1053,7 +1053,9 @@ def test_base_proxy_event_json_body_key_error():
def test_base_proxy_event_json_body():
data = {"message": "Foo"}
event = BaseProxyEvent({"body": json.dumps(data)})
assert event._parsed_json_body is None
assert event.json_body == data
assert event.json_body == event._parsed_json_body == data


def test_base_proxy_event_decode_body_key_error():
Expand Down Expand Up @@ -1084,7 +1086,7 @@ def test_base_proxy_event_json_body_with_base64_encoded_data():
event = BaseProxyEvent({"body": encoded_data, "isBase64Encoded": True})

# WHEN calling json_body
# THEN then base64 decode and json load
# THEN base64 decode and json load
assert event.json_body == data


Expand Down