// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 package software.amazonaws.example.product.entrypoints import com.amazonaws.services.lambda.runtime.Context import com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPEvent import com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPResponse import com.fasterxml.jackson.core.JsonProcessingException import groovy.transform.CompileStatic import org.slf4j.Logger import org.slf4j.LoggerFactory import software.amazon.lambda.powertools.tracing.Tracing import software.amazonaws.example.product.model.Product import software.amazonaws.example.product.store.ProductStore import software.amazonaws.example.product.store.dynamodb.DynamoDbProductStore import static groovy.json.JsonOutput.toJson import static software.amazon.awssdk.http.HttpStatusCode.* @CompileStatic class ApiGatewayGetProductRequestHandler implements ApiGatewayRequestHandler { private static final Logger logger = LoggerFactory.getLogger(ApiGatewayGetProductRequestHandler.class) private static final ProductStore productStore = new DynamoDbProductStore() @Override @Tracing APIGatewayV2HTTPResponse handleRequest(APIGatewayV2HTTPEvent event, Context context) { String id = event.pathParameters["id"] if (!id) { logger.warn("Missing 'id' parameter in path") return prepareResponse(BAD_REQUEST, /{ "message": "Missing 'id' parameter in path" }/) } logger.info("Fetching product $id") Optional product = productStore.getProduct(id) if (product.isEmpty()) { logger.warn("No product with id: {}", id) return prepareResponse(NOT_FOUND, '{"message": "Product not found"}') } logger.info product.toString() try { return prepareResponse(OK, toJson(product.get())) } catch (JsonProcessingException e) { logger.error e.message return prepareResponse(INTERNAL_SERVER_ERROR, '{"message": "Error processing JSON response"}') } } }