How to invoke a lambda function from another lambda in serverless offline?
Asked Answered
T

1

5

I'm trying to invoke a lambda function within the lambda function using Serverless framework. I'm using this code right now and it works fine when deployed to AWS. But it returns some errors locally in serverless-offline.

Code I'm using right now:

const middy = require("@middy/core");
const httpErrorHandler = require("@middy/http-error-handler");
const httpUrlEncodeBodyParser = require("@middy/http-urlencode-body-parser");

const AWS = require("aws-sdk");

const lambda = new AWS.Lambda();

const baseHandler = async (payload) => {
  const params = {
    FunctionName: `my-api-${process.env.STAGE}-handleProcessA`,
    InvocationType: "Event",
    LogType: "None",
    Payload: JSON.stringify(payload),
  };

  await lambda.invoke(params).promise();

  return standardResponse();
}

const endpoint = middy(baseHandler)
  .use(httpUrlEncodeBodyParser())
  .use(httpErrorHandler());

module.exports = { endpoint };

When this is triggered, it says that the function is not found: Function not found: arn:aws:lambda:us-west-2:893853743015:function:my-api-local-handleProcessA

I tried the suggestions from these SO questions as well: https://mcmap.net/q/2030253/-unable-to-invoke-a-lambda-from-another-lambda-using-aws-serverless-offline https://mcmap.net/q/2030254/-quot-unsupported-media-type-quot-using-serverless-offline

Based on the suggestions, I changed this part:

const lambda = new AWS.Lambda({
  region: "us-west-2",
  endpoint: process.env.IS_OFFLINE
    ? "http://localhost:6002"
    : "https://lambda.us-west-2.amazonaws.com",
});

But then, it gives me Unsupported Media Type with status 415. Has anyone encountered this before? Any guidance is appreciated.

Thanks.

Tucana answered 14/9, 2022 at 14:37 Comment(0)
T
10

Finally, I figured out the solution with some help. This works when I change the offline endpoint to be http://localhost:3002: where 3002 is the default lambdaPort.

const lambda = new AWS.Lambda({
  region: "us-west-2",
  endpoint: process.env.IS_OFFLINE
    ? "http://localhost:3002"
    : "https://lambda.us-west-2.amazonaws.com",
});

Explanation:

In serverless offline, there are CLI options to set the --lambdaPort and --httpPort.

The default --httpPort is 3000 and the default --lambdaPort is 3002.

In my project, I have set the --httpPort to be 6002 without custom --lambdaPort which defaulted to 3002.

I was invoking the lambda function using 6002 which was incorrect. Using 3002 solved it.

Tucana answered 16/9, 2022 at 5:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.