Skip to content
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

feat: Easy Event Deserialization #757

Merged
merged 16 commits into from
Mar 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
244 changes: 243 additions & 1 deletion docs/utilities/serialization.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,249 @@ title: Serialization Utilities
description: Utility
---

This module contains a set of utilities you may use in your Lambda functions, mainly associated with other modules like [validation](validation.md) and [idempotency](idempotency.md), to manipulate JSON.
This module contains a set of utilities you may use in your Lambda functions, to manipulate JSON.

## Easy deserialization

### Key features

* Easily deserialize the main content of an event (for example, the body of an API Gateway event)
* 15+ built-in events (see the [list below](#built-in-events))

### Getting started

=== "Maven"
jeromevdl marked this conversation as resolved.
Show resolved Hide resolved

```xml hl_lines="5"
<dependencies>
...
<dependency>
<groupId>software.amazon.lambda</groupId>
<artifactId>powertools-serialization</artifactId>
<version>{{ powertools.version }}</version>
</dependency>
...
</dependencies>
```

=== "Gradle"

```
implementation 'software.amazon.lambda:powertools-serialization:{{ powertools.version }}'
```

### EventDeserializer

The `EventDeserializer` can be used to extract the main part of an event (body, message, records) and deserialize it from JSON to your desired type.

It can handle single elements like the body of an API Gateway event:

=== "APIGWHandler.java"

```java hl_lines="1 6 9"
import static software.amazon.lambda.powertools.utilities.EventDeserializer.extractDataFrom;

public class APIGWHandler implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {

public APIGatewayProxyResponseEvent handleRequest(
final APIGatewayProxyRequestEvent event,
final Context context) {

Product product = extractDataFrom(event).as(Product.class);

}
```

=== "Product.java"

```java
public class Product {
private long id;
private String name;
private double price;

public Product() {
}

public Product(long id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
}

public long getId() {
return id;
}

public void setId(long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public double getPrice() {
return price;
}

public void setPrice(double price) {
this.price = price;
}
}
```

=== "event"

```json hl_lines="2"
{
"body": "{\"id\":1234, \"name\":\"product\", \"price\":42}",
"resource": "/{proxy+}",
"path": "/path/to/resource",
"httpMethod": "POST",
"isBase64Encoded": false,
"queryStringParameters": {
"foo": "bar"
},
"pathParameters": {
"proxy": "/path/to/resource"
},
"stageVariables": {
"baz": "qux"
},
"headers": {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, sdch",
"Accept-Language": "en-US,en;q=0.8",
"Cache-Control": "max-age=0",
"Host": "1234567890.execute-api.us-east-1.amazonaws.com",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Custom User Agent String",
"Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)",
"X-Amz-Cf-Id": "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==",
"X-Forwarded-For": "127.0.0.1, 127.0.0.2",
"X-Forwarded-Port": "443",
"X-Forwarded-Proto": "https"
},
"requestContext": {
"accountId": "123456789012",
"resourceId": "123456",
"stage": "prod",
"requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef",
"requestTime": "09/Apr/2015:12:34:56 +0000",
"requestTimeEpoch": 1428582896000,
"identity": {
"cognitoIdentityPoolId": null,
"accountId": null,
"cognitoIdentityId": null,
"caller": null,
"accessKey": null,
"sourceIp": "127.0.0.1",
"cognitoAuthenticationType": null,
"cognitoAuthenticationProvider": null,
"userArn": null,
"userAgent": "Custom User Agent String",
"user": null
},
"path": "/prod/path/to/resource",
"resourcePath": "/{proxy+}",
"httpMethod": "POST",
"apiId": "1234567890",
"protocol": "HTTP/1.1"
}
}
```

It can also handle a collection of elements like the records of an SQS event:

=== "SQSHandler.java"

```java hl_lines="1 6 9"
import static software.amazon.lambda.powertools.utilities.EventDeserializer.extractDataFrom;

public class SQSHandler implements RequestHandler<SQSEvent, String> {

public String handleRequest(
final SQSEvent event,
final Context context) {

List<Product> products = extractDataFrom(event).asListOf(Product.class);

}
```

=== "event"

```json hl_lines="6 23"
{
"Records": [
{
"messageId": "d9144555-9a4f-4ec3-99a0-34ce359b4b54",
"receiptHandle": "13e7f7851d2eaa5c01f208ebadbf1e72==",
"body": "{ \"id\": 1234, \"name\": \"product\", \"price\": 42}",
"attributes": {
"ApproximateReceiveCount": "1",
"SentTimestamp": "1601975706495",
"SenderId": "AROAIFU437PVZ5L2J53F5",
"ApproximateFirstReceiveTimestamp": "1601975706499"
},
"messageAttributes": {
},
"md5OfBody": "13e7f7851d2eaa5c01f208ebadbf1e72",
"eventSource": "aws:sqs",
"eventSourceARN": "arn:aws:sqs:eu-central-1:123456789012:TestLambda",
"awsRegion": "eu-central-1"
},
{
"messageId": "d9144555-9a4f-4ec3-99a0-34ce359b4b54",
"receiptHandle": "13e7f7851d2eaa5c01f208ebadbf1e72==",
"body": "{ \"id\": 12345, \"name\": \"product5\", \"price\": 45}",
"attributes": {
"ApproximateReceiveCount": "1",
"SentTimestamp": "1601975706495",
"SenderId": "AROAIFU437PVZ5L2J53F5",
"ApproximateFirstReceiveTimestamp": "1601975706499"
},
"messageAttributes": {

},
"md5OfBody": "13e7f7851d2eaa5c01f208ebadbf1e72",
"eventSource": "aws:sqs",
"eventSourceARN": "arn:aws:sqs:eu-central-1:123456789012:TestLambda",
"awsRegion": "eu-central-1"
}
]
}
```

!!! Tip
In the background, `EventDeserializer` is using Jackson. The `ObjectMapper` is configured in `JsonConfig`. You can customize the configuration of the mapper if needed:
`JsonConfig.get().getObjectMapper()`. Using this feature, you don't need to add Jackson to your project and create another instance of `ObjectMapper`.

### Built-in events

| Event Type | Path to the content | List |
|---------------------------------------------------|-----------------------------------------------------------|------|
| `APIGatewayProxyRequestEvent` | `body` | |
| `APIGatewayV2HTTPEvent` | `body` | |
| `SNSEvent` | `Records[0].Sns.Message` | |
| `SQSEvent` | `Records[*].body` | x |
| `ScheduledEvent` | `detail` | |
| `ApplicationLoadBalancerRequestEvent` | `body` | |
| `CloudWatchLogsEvent` | `powertools_base64_gzip(data)` | |
| `CloudFormationCustomResourceEvent` | `resourceProperties` | |
| `KinesisEvent` | `Records[*].kinesis.powertools_base64(data)` | x |
| `KinesisFirehoseEvent` | `Records[*].powertools_base64(data)` | x |
| `KafkaEvent` | `records[*].values[*].powertools_base64(value)` | x |
| `ActiveMQEvent` | `messages[*].powertools_base64(data)` | x |
| `RabbitMQEvent` | `rmqMessagesByQueue[*].values[*].powertools_base64(data)` | x |
| `KinesisAnalyticsFirehoseInputPreprocessingEvent` | `Records[*].kinesis.powertools_base64(data)` | x |
| `KinesisAnalyticsStreamsInputPreprocessingEvent` | `Records[*].kinesis.powertools_base64(data)` | x |


## JMESPath functions

Expand Down
6 changes: 6 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<lambda.core.version>1.2.1</lambda.core.version>
<lambda.events.version>3.11.0</lambda.events.version>
<lambda.serial.version>1.0.0</lambda.serial.version>
<maven-compiler-plugin.version>3.10.0</maven-compiler-plugin.version>
<aspectj-maven-plugin.version>1.14.0</aspectj-maven-plugin.version>
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
Expand Down Expand Up @@ -122,6 +123,11 @@
<artifactId>aws-lambda-java-events</artifactId>
<version>${lambda.events.version}</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-serialization</artifactId>
<version>${lambda.serial.version}</version>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>bom</artifactId>
Expand Down
13 changes: 13 additions & 0 deletions powertools-serialization/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,14 @@
<groupId>io.burt</groupId>
<artifactId>jmespath-jackson</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-events</artifactId>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In v4 of the events lib, there will be a dependency on Jackson, I don't think that changes anything, just worth noting.

</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
</dependency>

<!-- Test dependencies -->
<dependency>
Expand All @@ -57,6 +65,11 @@
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-tests</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
* Copyright 2022 Amazon.com, Inc. or its affiliates.
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package software.amazon.lambda.powertools.utilities;

public class EventDeserializationException extends RuntimeException {
private static final long serialVersionUID = -5003158148870110442L;

public EventDeserializationException(String msg, Exception e) {
super(msg, e);
}

public EventDeserializationException(String msg) {
super(msg);
}
}
Loading