Skip to content

Commit 6bda0f5

Browse files
committed
feat: add custom jmespath functions support
1 parent 080c9fd commit 6bda0f5

File tree

2 files changed

+17
-5
lines changed

2 files changed

+17
-5
lines changed

aws_lambda_powertools/utilities/validation/base.py

+13-2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import json
12
from typing import Dict
23

34
import fastjsonschema
@@ -6,6 +7,13 @@
67

78
try:
89
import jmespath
10+
11+
class PowertoolsJson(jmespath.functions.Functions):
12+
@jmespath.functions.signature({"types": ["string"]})
13+
def _func_powertools_json(self, value):
14+
return json.loads(value)
15+
16+
917
except ModuleNotFoundError:
1018
jmespath = None
1119

@@ -20,11 +28,14 @@ def validate_data_against_schema(data: Dict, schema: Dict):
2028
raise InvalidSchemaError(e)
2129

2230

23-
def unwrap_event_from_envelope(data: Dict, envelope: str):
31+
def unwrap_event_from_envelope(data: Dict, envelope: str, jmespath_options: Dict):
2432
if not jmespath:
2533
raise ModuleNotFoundError("This feature require aws-lambda-powertools[jmespath] extra package")
2634

35+
if not jmespath_options:
36+
jmespath_options = {"custom_functions": PowertoolsJson()}
37+
2738
try:
28-
return jmespath.search(envelope, data)
39+
return jmespath.search(envelope, data, options=jmespath.Options(**jmespath_options))
2940
except jmespath.exceptions.LexerError as e:
3041
raise InvalidEnvelopeExpressionError(e)

aws_lambda_powertools/utilities/validation/validator.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,13 @@ def validator(
1616
inbound_schema: Dict = None,
1717
outbound_schema: Dict = None,
1818
envelope: str = None,
19+
jmespath_options: Dict = None,
1920
):
2021
if isinstance(event, str):
2122
event = json.loads(event)
2223

2324
if envelope:
24-
event = unwrap_event_from_envelope(data=event, envelope=envelope)
25+
event = unwrap_event_from_envelope(data=event, envelope=envelope, jmespath_options=jmespath_options)
2526

2627
if inbound_schema:
2728
logger.debug("Validating inbound event")
@@ -36,9 +37,9 @@ def validator(
3637
return response
3738

3839

39-
def validate(event: Dict, schema: Dict = None, envelope: str = None):
40+
def validate(event: Dict, schema: Dict = None, envelope: str = None, jmespath_options: Dict = None):
4041
if envelope:
41-
event = unwrap_event_from_envelope(data=event, envelope=envelope)
42+
event = unwrap_event_from_envelope(data=event, envelope=envelope, jmespath_options=jmespath_options)
4243

4344
if isinstance(event, str):
4445
event = json.loads(event)

0 commit comments

Comments
 (0)