10

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.

2 Answers 2

16

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.

Sign up to request clarification or add additional context in comments.

Comments

0

As described in this comment from the GitHub issue logged by the OP, if you are using Node.js you can use this approach.

const data = JSON.parse(Buffer.from(Payload));

// if using TypeScript 
const data = JSON.parse(Buffer.from(Payload).toString());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.