4
4
import functools
5
5
import logging
6
6
import os
7
- from typing import Any , Callable , Dict , Optional , cast
7
+ from inspect import isclass
8
+ from typing import Any , Callable , Dict , Optional , Type , Union , cast
8
9
9
10
from aws_lambda_powertools .middleware_factory import lambda_handler_decorator
10
11
from aws_lambda_powertools .shared import constants
14
15
from aws_lambda_powertools .utilities .idempotency .persistence .base import (
15
16
BasePersistenceLayer ,
16
17
)
17
- from aws_lambda_powertools .utilities .idempotency .serialization .base import BaseIdempotencySerializer
18
+ from aws_lambda_powertools .utilities .idempotency .serialization .base import (
19
+ BaseIdempotencyModelSerializer ,
20
+ BaseIdempotencySerializer ,
21
+ )
18
22
from aws_lambda_powertools .utilities .typing import LambdaContext
19
23
20
24
logger = logging .getLogger (__name__ )
@@ -86,7 +90,7 @@ def idempotent_function(
86
90
data_keyword_argument : str ,
87
91
persistence_store : BasePersistenceLayer ,
88
92
config : Optional [IdempotencyConfig ] = None ,
89
- output_serializer : Optional [BaseIdempotencySerializer ] = None ,
93
+ output_serializer : Optional [Union [ BaseIdempotencySerializer , Type [ BaseIdempotencyModelSerializer ]] ] = None ,
90
94
) -> Any :
91
95
"""
92
96
Decorator to handle idempotency of any function
@@ -101,9 +105,11 @@ def idempotent_function(
101
105
Instance of BasePersistenceLayer to store data
102
106
config: IdempotencyConfig
103
107
Configuration
104
- output_serializer: Optional[BaseIdempotencySerializer]
108
+ output_serializer: Optional[Union[ BaseIdempotencySerializer, Type[BaseIdempotencyModelSerializer]] ]
105
109
Serializer to transform the data to and from a dictionary.
106
- If not supplied, no serialization is done via the NoOpSerializer
110
+ If not supplied, no serialization is done via the NoOpSerializer.
111
+ In case a serializer of type inheriting BaseIdempotencyModelSerializer] is given,
112
+ the serializer is deduced from the function return type.
107
113
Examples
108
114
--------
109
115
**Processes an order in an idempotent manner**
@@ -131,6 +137,9 @@ def process_order(customer_id: str, order: dict, **kwargs):
131
137
output_serializer = output_serializer ,
132
138
),
133
139
)
140
+ if isclass (output_serializer ) and issubclass (output_serializer , BaseIdempotencyModelSerializer ):
141
+ # instantiate an instance of the serializer class
142
+ output_serializer = output_serializer .instantiate (function .__annotations__ .get ("return" , None ))
134
143
135
144
config = config or IdempotencyConfig ()
136
145
0 commit comments