From 8420f96ffd6201656e908d6d7f61cdbbc3331cc1 Mon Sep 17 00:00:00 2001 From: Eli Polonsky Date: Thu, 2 Jul 2020 19:30:38 +0300 Subject: [PATCH] fix(apigateway): Lambda integration for imported functions (#8870) Use `instanceof` to identify real functions vs imported ones and appropriately use whats needed to extract the function name. Fixes #8869 ---- *By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license* --- .../aws-apigateway/lib/integrations/lambda.ts | 16 +++++++++++++--- .../aws-apigateway/test/test.lambda.ts | 19 +++++++++++++++++++ 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/packages/@aws-cdk/aws-apigateway/lib/integrations/lambda.ts b/packages/@aws-cdk/aws-apigateway/lib/integrations/lambda.ts index 7464232286786..c6a8ec04863c7 100644 --- a/packages/@aws-cdk/aws-apigateway/lib/integrations/lambda.ts +++ b/packages/@aws-cdk/aws-apigateway/lib/integrations/lambda.ts @@ -73,10 +73,20 @@ export class LambdaIntegration extends AwsIntegration { }); } - const cfnFunction = this.handler.node.defaultChild as lambda.CfnFunction; + let functionName; + + if (this.handler instanceof lambda.Function) { + // if not imported, extract the name from the CFN layer to reach + // the literal value if it is given (rather than a token) + functionName = (this.handler.node.defaultChild as lambda.CfnFunction).functionName; + } else { + // imported, just take the function name. + functionName = this.handler.functionName; + } + let deploymentToken; - if (!Token.isUnresolved(cfnFunction.functionName)) { - deploymentToken = JSON.stringify({ functionName: cfnFunction.functionName }); + if (!Token.isUnresolved(functionName)) { + deploymentToken = JSON.stringify({ functionName }); } return { ...bindResult, diff --git a/packages/@aws-cdk/aws-apigateway/test/test.lambda.ts b/packages/@aws-cdk/aws-apigateway/test/test.lambda.ts index afc1a2230e848..b518db5a29bc9 100644 --- a/packages/@aws-cdk/aws-apigateway/test/test.lambda.ts +++ b/packages/@aws-cdk/aws-apigateway/test/test.lambda.ts @@ -259,4 +259,23 @@ export = { test.done(); }, + + 'bind works for integration with imported functions'(test: Test) { + // GIVEN + const stack = new cdk.Stack(); + const restapi = new apigateway.RestApi(stack, 'RestApi'); + const method = restapi.root.addMethod('ANY'); + const handler = lambda.Function.fromFunctionArn(stack, 'MyFunc', 'arn:aws:lambda:region:account:function:myfunc'); + const integration = new apigateway.LambdaIntegration(handler); + + // WHEN + const bindResult = integration.bind(method); + + // the deployment token should be defined since the function name + // should be a literal string. + test.equal(bindResult?.deploymentToken, JSON.stringify({functionName: 'myfunc'})); + + test.done(); + }, + };