Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@aws-sdk/client-lambda] - Invoke Lambda - Payload Response in Unit8Array - Convert to String

I am using the @aws-sdk/client-lambda npm package for invoking lambdas. I have two Lambdas. Lambda A & Lambda B. Lambda A is trying to invoke Lambda B.

Lambda A invokes Lambda B by running the following code:

const { LambdaClient, InvokeCommand } = require('@aws-sdk/client-lambda');

module.exports = {
  getGitHubToken: async () => {
    const client = new LambdaClient({ region: process.env.REGION });

    const params = {
      FunctionName: process.env.GITHUB_TOKEN_FUNCTION,
      LogType: 'Tail',
      Payload: '',
    };

    const command = new InvokeCommand(params);

    try {
      const { Payload } = await client.send(command);
      console.log(Payload);
      return Payload;
    } catch (error) {
      console.error(error.message);
      throw error;
    }
  },
};

The expected response from Lambda B should look like this:

{
  statusCode: 200,
  body: JSON.stringify({
    token: '123',
  }),
};

However, Payload looks to be returning this from the line console.log(Payload);:

Response

I looked on the AWS SDK Website and it looks like Payload returns a Uint8Array. I guess this is because it's from a promise?

I have tried doing Payload.toString() however that comes back as simply a string of the values in the Unit8Array. Example being:

2021-04-13T14:32:04.874Z worker:success Payload: 123,34,115,116,97,116,117,115,67,111,100,101,34,58,50,48,48,44,34,98,111,100,121,34,58,34,123,92,34,116,111,107,101,110,92,34,58,92,34,103,104,115,95,111,114,101,51,65,109,99,122,86,85,74,122,66,52,90,68,104,57,122,122,85,118,119,52,51,50,111,67,71,48,50,75,121,79,69,72,92,34,125,34,125

My Question:

How do I resolve data from Unit8Array to the data I was expecting from the Lambda response? Which is a JSON Object?

I have confirmed the requested Lambda (Lambda B in this case) is returning the data correctly by going to CloudWatch. Thanks.

like image 617
user3180997 Avatar asked Mar 01 '23 15:03

user3180997


1 Answers

Okay, I found a way to get this working.

You have to specify a text encoder:

const asciiDecoder = new TextDecoder('ascii');

Then decode it so it looks like this:

const data = asciiDecoder.decode(Payload);

I have logged an issue on their repository asking why this isn't included in the module. I will post an update on any movement on this.

like image 87
user3180997 Avatar answered May 19 '23 00:05

user3180997