Skip to content

Instantly share code, notes, and snippets.

@FRosner
Created February 2, 2023 13:27
Show Gist options
  • Save FRosner/13c29d444b2b38354fa6af12835810b5 to your computer and use it in GitHub Desktop.
Save FRosner/13c29d444b2b38354fa6af12835810b5 to your computer and use it in GitHub Desktop.
public class LambdaHandler implements RequestHandler<APIGatewayV2HTTPEvent, LambdaResponse> {
private static final Gson mapper = new Gson();
private static final AstraClient astraClient = newAstraClientFromEnv();
private static AstraClient newAstraClientFromEnv() {
String astraUrl = System.getenv("ASTRA_URL");
String astraToken = System.getenv("ASTRA_TOKEN");
String astraNamespace = System.getenv("ASTRA_NAMESPACE");
return new AstraClient(URI.create(astraUrl), astraToken, astraNamespace);
}
@Override
public LambdaResponse handleRequest(APIGatewayV2HTTPEvent input, Context context) {
if (input.getRouteKey().startsWith("GET")) {
String orderIdRaw = input.getPathParameters().get("orderId");
UUID orderId = UUID.fromString(orderIdRaw);
Optional<Order> order = astraClient.getOrder(orderId);
if (order.isEmpty()) {
return new LambdaResponse();
}
return new LambdaResponse(order.get());
} else if (input.getRouteKey().startsWith("POST")) {
Order requestOrder = null;
try {
byte[] decodedRequest = base64DecodeApiGatewayEvent(input);
requestOrder = mapper.fromJson(new String(decodedRequest), Order.class);
Order savedOrder = astraClient.saveOrder(requestOrder);
LambdaResponse lambdaResponse = new LambdaResponse(savedOrder);
return lambdaResponse;
} catch (Exception e) {
logger.log("Could not save input '" + input + "' as order '" + requestOrder);
logger.log("Exception was: " + e.getLocalizedMessage());
return new LambdaResponse(
"{ \"message\": \"Order could not be saved.\" }",
SC_BAD_REQUEST);
}
} else {
return new LambdaResponse(
"{ \"message\": \"HTTP method is not supported.\" }",
SC_BAD_REQUEST);
}
}
private byte[] base64DecodeApiGatewayEvent(APIGatewayV2HTTPEvent input) {
byte[] decodedRequest;
if (input.getIsBase64Encoded()) {
decodedRequest = Base64.decodeBase64(input.getBody());
} else {
String body = input.getBody();
decodedRequest = body != null ? body.getBytes(UTF_8) : null;
}
return decodedRequest;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment