Whilst building a new LambdaFunction, with the AWS CDK aws-lib
, I am encountering an issue when integrating the Lambda with the httpApi
on API Gateway.
Expected result: Have a Lambda function trigger upon posting to a method on the httpApi
resource.
Error message: "TypeError: Cannot read properties of undefined (reading ‘functionArn’)"
Lambda Function:
async function handler(event) {
return {
body: JSON.stringify({ message: "SUCCESS " }),
statusCode: 200,
};
}
module.exports = { handler };
Lambda Stack:
export class LambdaStack extends Stack {
public readonly lambdaFunction: LambdaFunction;
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
const resourceEnvironment: ResourceEnvironment = {
account: Stack.of(this).account,
region: Stack.of(this).region,
};
const lambdaFunction = new LambdaFunction(
this,
"lambdaFunction",
{
runtime: Runtime.NODEJS_16_X,
memorySize: 1024,
timeout: Duration.minutes(15),
handler: "index.handler",
code: Code.fromAsset(
join(__dirname, "../services/lambdaFunction")
),
environment: {
REGION: Stack.of(this).region,
AVAILABILITY_ZONES: JSON.stringify(Stack.of(this).availabilityZones),
addCommandUserLambdaArn: "",
},
}
);
}
}
AWS API Gateway Integration:
interface ApiProps extends StackProps {
lambdaStack: LambdaStack;
}
export class ApiStack extends Stack {
declare restApi: Resource;
constructor(scope: Construct, id: string, props: ApiProps) {
super(scope, id, props);
const { lambdaStack } = props;
const lambdaFunctionIntegration = new HttpLambdaIntegration(
"lambdaFunctionIntegration",
lambdaStack.lambdaFunction
);
const httpApi = new HttpApi(this, "HttpApi", {
apiName: "intoNS",
corsPreflight: {
allowHeaders: [
"Content-Type",
"X-Amz-Date",
"Authorization",
"X-Api-Key",
],
allowMethods: [CorsHttpMethod.OPTIONS, CorsHttpMethod.POST],
allowOrigins: ["*"],
maxAge: Duration.days(10),
},
});
httpApi.addRoutes({
path: "/infoFIFO",
methods: [HttpMethod.POST],
integration: lambdaFunctionIntegration,
});
}
}
2
Answers
After declaring
const lambdaFunction
, I needed to write this code:According to aws cdk docs you need to specify :
functionArn - string - ARN of this function.
Also refer developer docs for example :