How to trace a lambda invokes a lambda with AWS X-Ray? - node.js

I have an AWS Lambda function which is triggered by an API Gateway event. The API Gateway is configured to use X-Ray.
As the Lambda tracing configuration defaults to PassTrough it is also shown in X-Ray (service map, etc.).
The invoked Lambda uses the node.js aws-sdk to invoke another lambda. If I understand correctly the Tracing ID has to be passed on to the next Invocation in order to show this Lambda also in X-Ray. In the API of the SDK I found no option for this.
const result = await lambda
.invoke(lambdaParamsCreateUser)
.promise()
How can I achieve this? How can I trace also the invocation of the original request?
With the tips of #Balu Vyamajala I changed the AWS-SDK import to the following:
import AWS from "aws-sdk";
import AwsXRay from "aws-xray-sdk-core";
const aws = AwsXRay.captureAWS(AWS);
export default aws;
I use it when I invoice my second function like this:
import AWS from "aws";
const Lambda = AWS.Lambda;
// ...
const lambda = new Lambda({ region: "eu-central-1" });
const lambdaPromise = lambda
.invoke({
FunctionName: AUTH_CREATE_USER_FUNC,
InvocationType: "RequestResponse",
Qualifier: AUTH_CREATE_USER_FUNC_VERSION,
Payload: JSON.stringify({
eMail: eMail,
device: device,
customerId: customerId,
}),
LogType: "Tail",
})
.promise()
But in X-Ray there is no invocation chain :-(
https://imgur.com/wDMlNzb
Do I make a mistake?

if we enable X-Ray for both Lambda functions , trace-id is automatically passed and will be same for both Lambdas.
In the code, we can enable X-Ray simply by wrapping it around aws-sdk
JavaScript:
const AWSXRay = require("aws-xray-sdk-core");
const AWS = AWSXRay.captureAWS(require("aws-sdk"));
Typescript:
import AWSXRay from 'aws-xray-sdk';
import aws from 'aws-sdk';
const AWS = AWSXRay.captureAWS(aws)
Here is a sample test to confirm.
balu-test >> sample-test
Lambda 1 (balu-test) :
const AWSXRay = require("aws-xray-sdk-core");
const AWS = AWSXRay.captureAWS(require("aws-sdk"));
const lambda = new AWS.Lambda();
exports.handler = async function (event, context) {
var params = {
FunctionName: "sample-test",
InvocationType: "RequestResponse",
Payload: '{ "name" : "foo" }',
};
const response = await lambda.invoke(params).promise();
console.log('response',response);
return "sucess";
};
Lambda 2(sample-test):
const AWSXRay = require("aws-xray-sdk-core");
const AWS = AWSXRay.captureAWS(require("aws-sdk"));
let region = "us-east-1"
let secretName = "SomeSecret"
let secret
let decodedBinarySecret
var client = new AWS.SecretsManager({
region: region,
});
exports.handler = (event, context, callback) => {
client.getSecretValue({ SecretId: secretName }, function (err, data) {
if (err) {
callback(err);
} else {
if ("SecretString" in data) {
secret = data.SecretString;
} else {
let buff = new Buffer(data.SecretBinary, "base64");
decodedBinarySecret = buff.toString("ascii");
}
callback(null, secret);
}
});
};
TraceId is same and X-Ray points to same graph for both Lambda invocations. Same thing happens when first api is called from Api-Gateway. First time trace-id is generated and is passed along as http header to downstream processes.

Related

AWS textract methods in node js are not getting invoked

I want to extract text from image using node js so created a lambda in aws. Please find the below code snippet. Issue is that the textract method detectDocumentText is not getting invoked.
As far as permission I had given s3 full access and textract full access to the lambda. Am I missing anything?
var AWS = require("aws-sdk");
var base64 = require("base-64");
var fs = require("fs");
exports.handler = async (event, context, callback) => {
// Input for textract can be byte array or S3 object
AWS.config.region = "us-east-1";
//AWS.config.update({ region: 'us-east-1' });
var textract = new AWS.Textract({ apiVersion: "2018-06-27" });
//var textract = new AWS.Textract();
console.log(textract);
var params = {
Document: {
/* required */
//'Bytes': imageBase64
S3Object: {
Bucket: "717577",
Name: "Picture2.png"
}
}
};
textract.detectDocumentText(params, function(err, data) {
if (err) {
console.log(err); // an error occurred
} else {
console.log(data); // successful response
callback(null, data);
}
});
};
As well as I don't see any error logs in cloudwatch logs.
The problem is that you have marked your method as async which means that you are returning a promise. In your case you are not returning a promise so for lambda there is no way to complete the execution of the method. You have two choices here
Remove async
Or more recommended way is to convert your callback style to use promise. aws-sdk support .promise method on all methods so you could leverage that. The code will look like this
var AWS = require("aws-sdk");
var base64 = require("base-64");
var fs = require("fs");
exports.handler = async (event, context) => {
// Input for textract can be byte array or S3 object
AWS.config.region = "us-east-1";
//AWS.config.update({ region: 'us-east-1' });
var textract = new AWS.Textract({ apiVersion: "2018-06-27" });
//var textract = new AWS.Textract();
console.log(textract);
var params = {
Document: {
/* required */
//'Bytes': imageBase64
S3Object: {
Bucket: "717577",
Name: "Picture2.png"
}
}
};
const data = await textract.detectDocumentText(params).promise();
return data;
};
Hope this helps.

AWS NodeJS lambda call within a lambda function

I've trying to call lambda function from another lambda function and get result to execute rest of the lambda.
Basic flow of function is below
X - main lambda function
- process A (independent)
- process C (need input from process B)
- process D
- return final dataset
Y - Child lambda function
- process B ( need input from process A and respond back to X )
This is my code so far
var AWS = require('aws-sdk');
AWS.config.region = 'us-east-1';
var lambda = new AWS.Lambda();
const GetUserCheckoutData: Handler = async (userRequest: EmptyProjectRequest, context: Context, callback: Callback) => {
const dboperation = new UserController();
const usercheckoutdata = new CheckOutInfo();
const addresscontroller = new AddressController();
const ordercontroller = new OrderController();
const paypalcreateorder = new PayPalController();
const userid = await dboperation.getUserID(userRequest.invokeemailAddress);
usercheckoutdata.useraddressdetails = await addresscontroller.GetListOfAddressByUserID(userid);
var orderlist = new Array<Order>();
orderlist = [];
orderlist = await ordercontroller.GetCurrentOrder(userid);
console.log("Order Complete");
var params = {
FunctionName: 'api-ENGG-SellItem', // the lambda function we are going to invoke
InvocationType: 'RequestResponse',
LogType: 'Tail',
Payload: '{ "orderlist" : xxxxxxx }'
};
lambda.invoke(params, (err:any, res:any) => {
if (err) {
callback(err);
}
console.log(JSON.stringify(res));
callback(null, res.Payload);
});
usercheckoutdata.orderID = await paypalcreateorder.CreateOrder(userid , orderlist);
usercheckoutdata.orderPreview = await ordercontroller.OrderPreview(userid);
//callback(null,usercheckoutdata);
};
export { GetUserCheckoutData }
I tried a few different ways but flow is not working properly. cross lambda function is executing. but cannot get the response on time.
My child lambda function demo code
import { Handler, Context } from "aws-lambda";
const SellItem: Handler = (event, context, callback) => {
context.callbackWaitsForEmptyEventLoop = false;
console.log("Other Lambda Function");
setTimeout(() => {
callback(null, "My name is Jonathan");
}, 1000 * 10); // 10 seconds delay
}
export {SellItem}
I think since I don't have much NodeJS knowledge this is happening. don't know how to put call back in right way I guess. Any help will be appreciated
You should make your call to the second lambda a promise, so you can await it.
const res = await lambda.invoke(params).promise();
// do things with the response

To mock AWS SES with Sinon

I'm trying to mock SES with Sinon, but facing below error. Tried using aws-sdk-mock, but it's not working.
Error: TypeError: Cannot stub non-existent own property sendEmail
Code snippet of test class:
import * as AWS from 'aws-sdk';
const sandbox = sinon.createSandbox();
sandbox.stub(AWS.SES, 'sendEmail').returns({promise: () => true});
Actual class:
import * as AWS from 'aws-sdk';
import * as _ from 'lodash';
export async function sendAlertMailOnFailure(status:any)
{
// load AWS SES
var ses = new AWS.SES();
const params = {
Destination: {
ToAddresses: <to_address>
},
Message: {...},
Source: <sender_address>
}
ses.sendEmail(params, (err, data) => {
if (err) {
log.error("Error sending mail::");
log.error(err, err.stack);
}
})
}
Is there any way to mock SES with Sinon or with aws-sdk-mock?
My answer here is not a direct solution for SES, but it is a working solution I'm using for mocking DynamoDB.DocumentClient and SQS. Perhaps you can adapt my working example for SES and other aws-sdk clients in your unit tests.
I just spent hours trying to get AWS SQS mocking working, without resorting to the aws-sdk-mock requirement of importing aws-sdk clients inside a function.
The mocking for AWS.DynamoDB.DocumentClient was pretty easy, but the AWS.SQS mocking had me stumped until I came across the suggestion to use rewire.
My lambda moves bad messages to a SQS FailQueue (rather than letting the Lambda fail and return the message to the regular Queue for retries, and then DeadLetterQueue after maxRetries). The unit tests needed to mock the following SQS methods:
SQS.getQueueUrl
SQS.sendMessage
SQS.deleteMessage
I'll try to keep this example code as concise as I can while still including all the relevant parts:
Snippet of my AWS Lambda (index.js):
const AWS = require('aws-sdk');
AWS.config.update({region:'eu-west-1'});
const docClient = new AWS.DynamoDB.DocumentClient();
const sqs = new AWS.SQS({ apiVersion: '2012-11-05' });
// ...snip
Abridged Lambda event records (event.json)
{
"valid": {
"Records": [{
"messageId": "c292410d-3b27-49ae-8e1f-0eb155f0710b",
"receiptHandle": "AQEBz5JUoLYsn4dstTAxP7/IF9+T1S994n3FLkMvMmAh1Ut/Elpc0tbNZSaCPYDvP+mBBecVWmAM88SgW7iI8T65Blz3cXshP3keWzCgLCnmkwGvDHBYFVccm93yuMe0i5W02jX0s1LJuNVYI1aVtyz19IbzlVksp+z2RxAX6zMhcTy3VzusIZ6aDORW6yYppIYtKuB2G4Ftf8SE4XPzXo5RCdYirja1aMuh9DluEtSIW+lgDQcHbhIZeJx0eC09KQGJSF2uKk2BqTGvQrknw0EvjNEl6Jv56lWKyFT78K3TLBy2XdGFKQTsSALBNtlwFd8ZzcJoMaUFpbJVkzuLDST1y4nKQi7MK58JMsZ4ujZJnYvKFvgtc6YfWgsEuV0QSL9U5FradtXg4EnaBOnGVTFrbE18DoEuvUUiO7ZQPO9auS4=",
"body": "{ \"key1\": \"value 1\", \"key2\": \"value 2\", \"key3\": \"value 3\", \"key4\": \"value 4\", \"key5\": \"value 5\" }",
"attributes": {
"ApproximateReceiveCount": "1",
"SentTimestamp": "1536763724607",
"SenderId": "AROAJAAXYIAN46PWMV46S:steve.goossens#bbc.co.uk",
"ApproximateFirstReceiveTimestamp": "1536763724618"
},
"messageAttributes": {},
"md5OfBody": "e5b16f3a468e6547785a3454cfb33293",
"eventSource": "aws:sqs",
"eventSourceARN": "arn:aws:sqs:eu-west-1:123456789012:sqs-queue-name",
"awsRegion": "eu-west-1"
}]
}
}
Abridged unit test file (test/index.test.js):
const AWS = require('aws-sdk');
const expect = require('chai').expect;
const LamdbaTester = require('lambda-tester');
const rewire = require('rewire');
const sinon = require('sinon');
const event = require('./event');
const lambda = rewire('../index');
let sinonSandbox;
function mockGoodSqsMove() {
const promiseStubSqs = sinonSandbox.stub().resolves({});
const sqsMock = {
getQueueUrl: () => ({ promise: sinonSandbox.stub().resolves({ QueueUrl: 'queue-url' }) }),
sendMessage: () => ({ promise: promiseStubSqs }),
deleteMessage: () => ({ promise: promiseStubSqs })
}
lambda.__set__('sqs', sqsMock);
}
describe('handler', function () {
beforeEach(() => {
sinonSandbox = sinon.createSandbox();
});
afterEach(() => {
sinonSandbox.restore();
});
describe('when SQS message is in dedupe cache', function () {
beforeEach(() => {
// mock SQS
mockGoodSqsMove();
// mock DynamoDBClient
const promiseStub = sinonSandbox.stub().resolves({'Item': 'something'});
sinonSandbox.stub(AWS.DynamoDB.DocumentClient.prototype, 'get').returns({ promise: promiseStub });
});
it('should return an error for a duplicate message', function () {
return LamdbaTester(lambda.handler)
.event(event.valid)
.expectReject((err, additional) => {
expect(err).to.have.property('message', 'Duplicate message: {"Item":"something"}');
});
});
});
});
You need to use prototype in AWS to stub it:
import AWS from 'aws-sdk';
const sandbox = sinon.createSandbox();
sandbox.stub(AWS.prototype, 'SES').returns({
sendEmail: () => {
return true;
}
});
The error seems to indicate that AWS is being imported as undefined.
It might be that your ES6 compiler isn't automatically turning this line:
import AWS from 'aws-sdk';
...into an import of everything in aws-sdk into AWS.
Change it to this:
import * as AWS from 'aws-sdk';
...and that may fix the issue.
(Disclaimer: I can't reproduce the error in my environment which is compiling with Babel v7 and automatically handles either approach)
Using require & without using prototype. This is working for me for mocking DynamoDB.
const aws = require('aws-sdk');
const sinon = require('sinon');
const sandbox = sinon.createSandbox();
this.awsStub = sandbox.stub(aws, 'DynamoDB').returns({
query: function() {
return {
promise: function() {
return {
Items: []
};
}
};
}
});
Packages:
"aws-sdk": "^2.453.0"
"sinon": "^7.3.2"
I was able to use awk-sdk-mock by doing the following:
test class
const AWSMock = require('aws-sdk-mock');
const AWS = require('aws-sdk');
AWSMock.setSDKInstance(AWS);
...
AWSMock.mock('SES', 'sendRawEmail', mockSendEmail);
// call method that needs to mock send an email goes below
sendEmail(to, from, subject, body, callback);
function mockSendEmail(params, callback) {
console.log('mock email');
return callback({
MessageId: '1234567',
});
}
Actual class
const aws = require('aws-sdk');
const nodemailer = require('nodemailer');
function sendEmail(to, from, subject, body, callback) {
let addresses = to;
if (!Array.isArray(addresses)) {
addresses = [addresses];
}
let replyTo = [];
if (from) {
replyTo.push(from);
}
let data = {
to: addresses,
replyTo,
subject,
text: body,
};
nodemailer.createTransport({ SES: new aws.SES({ apiVersion: '2010-12-01' }) }).sendMail(data, callback);
}
const AWS = require('aws-sdk');
...
const sandbox = sinon.createSandbox();
sandbox.stub(AWS, 'SES').returns({
sendRawEmail: () => {
console.log("My sendRawEmail");
return {
promise: function () {
return {
MessageId: '987654321'
};
}
};
}
});
let ses = new AWS.SES({ region: 'us-east-1' });
let result = ses.sendRawEmail(params).promise();

Invoke lambda from code with same trace id?

I have simple lambda A calling lambda B, I need to pass amazon trace id to lambda B. Is it possible while using lambda.invoke? Do you have some simple example to do this in node.js?
Lambda A:
const AWS = require('aws-sdk');
AWS.config.region = process.env.AWS_REGION;
const lambda = new AWS.Lambda();
const params = {
FunctionName: 'lambda-b',
InvocationType: 'Event',
LogType: 'Tail',
Payload: '{ "name" : "janko" }'
};
const result = await lambda.invoke(params).promise();
console.log(`TraceId: ${process.env._X_AMZN_TRACE_ID}`);
In log of lambda A is 'TraceId: Root=1-5be30a84-31c7700e813851b25fad8b5a;Parent=6bcdc85668f474fb;Sampled=0'
In log of lambda B is: 'TraceId: Root=1-5be30a81-c552e60321963c04d75db028;Parent=30247b5d7680c581;Sampled=0'
I was unable to pass trace-id directly, however aim of passing trace-id was to see complete event flow in x-ray. You can achieve this by wrapping lambda.invoke (similarly send to SQS/SNS can be wrapped).
const AWSXRay = require('aws-xray-sdk');
const AWS = require('aws-sdk');
exports.handler = async (event) => {
const lambda = AWSXRay.captureAWSClient(new AWS.Lambda());
let params = {
FunctionName: `lambda-b`,
InvocationType: 'Event',
Payload: '{ "name" : "janko" }'
};
result = await lambda.invoke(params).promise();
};
Then you can see whole chain of calls in AWS X-Ray.

Nodejs - Invoke an AWS.Lambda function from within another lambda function

I have the following function which I use to invoke a Lambda function from within my code.
However when I try to use it within a Lambda function, I get the following error:
AWS lambda undefined 0.27s 3 retries] invoke({ FunctionName: 'my-function-name',
InvocationType: 'RequestResponse',
LogType: 'Tail',
Payload: <Buffer > })
How can I invoke a Lambda function from within a Lambda function?
My function:
'use strict';
var AWS = require("aws-sdk");
var lambda = new AWS.Lambda({
apiVersion: '2015-03-31',
endpoint: 'https://lambda.' + process.env.DYNAMODB_REGION + '.amazonaws.com',
logger: console
});
var lambdaHandler = {};
// #var payload - type:string
// #var functionName - type:string
lambdaHandler.invokeFunction = function (payload, functionName, callback) {
var params = {
FunctionName: functionName, /* required */
InvocationType: "RequestResponse",
LogType: "Tail",
Payload: new Buffer(payload, 'utf8')
};
var lambdaRequestObj = lambda.invoke(params);
lambdaRequestObj.on('success', function(response) {
console.log(response.data);
});
lambdaRequestObj.on('error', function(response) {
console.log(response.error.message);
});
lambdaRequestObj.on('complete', function(response) {
console.log('Complete');
});
lambdaRequestObj.send();
callback();
};
module.exports = lambdaHandler;
Invoking a Lambda Function from within another Lambda function is quite simple using the aws-sdk which is available in every Lambda.
I suggest starting with something simple first.
This is the "Hello World" of intra-lambda invocation:
Lambda_A invokes Lambda_B
with a Payload containing a single parameter name:'Alex'.
Lambda_B responds with Payload: "Hello Alex".
First create Lambda_B which expects a name property
on the event parameter
and responds to request with "Hello "+event.name:
Lambda_B
exports.handler = function(event, context) {
console.log('Lambda B Received event:', JSON.stringify(event, null, 2));
context.succeed('Hello ' + event.name);
};
Ensure that you give Lambda_B and Lambda_A the same role.
E.g: create a role called lambdaexecute which has AWSLambdaRole, AWSLambdaExecute and
AWSLambdaBasicExecutionRole (All are required):
Lambda_A
var AWS = require('aws-sdk');
AWS.config.region = 'eu-west-1';
var lambda = new AWS.Lambda();
exports.handler = function(event, context) {
var params = {
FunctionName: 'Lambda_B', // the lambda function we are going to invoke
InvocationType: 'RequestResponse',
LogType: 'Tail',
Payload: '{ "name" : "Alex" }'
};
lambda.invoke(params, function(err, data) {
if (err) {
context.fail(err);
} else {
context.succeed('Lambda_B said '+ data.Payload);
}
})
};
Once you have saved both these Lambda functions, Test run Lambda_A:
Once you have the basic intra-lambdda invocation working you can easily extend it to invoke more elaborate Lambda functions.
The main thing you have to remember is to set the appropriate ARN Role for all functions.
As of Dec 3, 2016, you can simply use an AWS Step function to put Lambda function Lambda_B as the sequential step of Lambda_A.
With AWS Step Functions, you define your application as a state
machine, a series of steps that together capture the behavior of the
app. States in the state machine may be tasks, sequential steps,
parallel steps, branching paths (choice), and/or timers (wait). Tasks
are units of work, and this work may be performed by AWS Lambda
functions, Amazon EC2 instances of any type, containers, or on
premises servers—anything that can communicate with the Step Functions
API may be assigned a task.
So the following state machine should meet your need.
Here is the code corresponding to the state machine.
{
"Comment": "A simple example of the Amazon States Language using an AWS Lambda Function",
"StartAt": "Lambda_A",
"States": {
"Lambda_A": {
"Type": "Task",
"Resource": "arn:aws:lambda:REGION:ACCOUNT_ID:function:FUNCTION_NAME",
"Next": "Lambda_B"
},
"Lambda_B":{
"Type": "Task",
"Resource": "arn:aws:lambda:REGION:ACCOUNT_ID:function:FUNCTION_NAME",
"End": true
}
}
}
Moreover, you can add much more sophisticated logics in a state machine, such as parallel steps and catch failures. It even logs the details of every single execution which makes debugging a much better experience, especially for lambda functions.
Everything mentioned by #nelsonic is correct, except for the roles.
I tried choosing the roles that he mentioned above:
AWSLambdaExecute
AWSLambdaBasicExecutionRole
But it did not allow me to invoke my other lambda function, so I changed the role to the below:
AWSLambdaRole
AWSLambdaBasicExecutionRole
The reason behind is AWSLambdaExecute only provides Put, Get access to S3 and full access to CloudWatch Logs.
but AWSLambdaRole provides Default policy for AWS Lambda service role.
if you observe its permission policy it will talk about the invokeFunction
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"lambda:InvokeFunction"
],
"Resource": [
"*"
]
}
]
}
Note: it is OK to proceed without AWSLambdaBasicExecutionRole policy as it only enables the logging in the cloud watch nothing much. But AWSLambdaRole is absolutely necessary.
It's easier to invoke a lambda using the AWS.Lambda promises interface in aws-sdk than using callbacks.
This example function lets you make a synchronous invocation of a lambda from another lambda (it uses 'RequestResponse' as InvocationType, so you'll can get the value returned by the invoked lambda).
If you use 'Event' (for asynchronous invocation), you can't get the value returned by the called lambda, only be able to detect whether the lambda could be invoked with success or not. It is intended for cases when you don't need to obtain a returned value from the invoked lambda.
//
// Full example of a lambda that calls another lambda
//
// (create a lambda in AWS with this code)
//
'use strict';
//
// Put here the name of the function you want to call
//
const g_LambdaFunctionName = 'PUT_HERE_THE_INVOKED_LAMBDA_NAME'; // <======= PUT THE DESIRED VALUE
const AWS = require('aws-sdk');
const lambda = new AWS.Lambda;
//
// Expected use:
//
// // (payload can be an object or a JSON string, for example)
// let var = await invokeLambda(lambdaFunctionName, payload);
//
const invokeLambda = async (lambdaFunctionName, payload) => {
console.log('>>> Entering invokeLambda');
// If the payload isn't a JSON string, we convert it to JSON
let payloadStr;
if (typeof payload === 'string')
{
console.log('invokeLambda: payload parameter is already a string: ', payload);
payloadStr = payload;
}
else
{
payloadStr = JSON.stringify(payload, null, 2);
console.log('invokeLambda: converting payload parameter to a string: ', payloadStr);
}
let params = {
FunctionName : lambdaFunctionName, /* string type, required */
// ClientContext : '', /* 'STRING_VALUE' */
InvocationType : 'RequestResponse', /* string type: 'Event' (async)| 'RequestResponse' (sync) | 'DryRun' (validate parameters y permissions) */
// InvocationType : 'Event',
LogType : 'None', /* string type: 'None' | 'Tail' */
// LogType : 'Tail',
Payload : payloadStr, /* Buffer.from('...') || 'JSON_STRING' */ /* Strings will be Base-64 encoded on your behalf */
// Qualifier : '', /* STRING_VALUE' */
};
//
// TODO/FIXME: add try/catch to protect this code from failures (non-existent lambda, execution errors in lambda)
//
const lambdaResult = await lambda.invoke(params).promise();
console.log('Results from invoking lambda ' + lambdaFunctionName + ': ' , JSON.stringify(lambdaResult, null, 2) );
// If you use LogType = 'Tail', you'll obtain the logs in lambdaResult.LogResult.
// If you use 'None', there will not exist that field in the response.
if (lambdaResult.LogResult)
{
console.log('Logs of lambda execution: ', Buffer.from(lambdaResult.LogResult, 'base64').toString());
}
console.log('invokeLambdaSync::lambdaResult: ', lambdaResult);
console.log('<<< Returning from invokeLambda, with lambdaResult: ', JSON.stringify(lambdaResult, null, 2));
// The actual value returned by the lambda it is lambdaResult.Payload
// There are other fields (some of them are optional)
return lambdaResult;
};
//
// We'll assign this as the calling lambda handler.
//
const callingFunc = async (event) => {
//
// in this example We obtain the lambda name from a global variable
//
const lambdaFunctionName = g_LambdaFunctionName;
// const payload = '{"param1" : "value1"}';
const payload = event;
//
// invokeLambda has to be called from a async function
// (to be able to use await)
//
const result = await invokeLambda(lambdaFunctionName, payload);
console.log('result: ', result);
};
// Assing handler function
exports.handler = callingFunc;
Notice that you should use await before invokeLambda:
...
//
// Called from another async function
//
const result = await invokeLambda(lambdaFunctionName, payload);
...
Some relevant links with additional information:
AWS Reference about invoke call: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Lambda.html#invoke-property
AWS documentation about invoking a lambda: https://docs.aws.amazon.com/lambda/latest/dg/API_Invoke.html
Promises interface in AWS:
https://aws.amazon.com/es/blogs/compute/node-js-8-10-runtime-now-available-in-aws-lambda/
Examples (explanations in Spanish): https://www.it-swarm.dev/es/node.js/invocar-aws-lambda-desde-otra-lambda-de-forma-asincronica/826852446/
Handling errors, avoiding coupling between lambdas: https://www.rehanvdm.com/serverless/13-aws-lambda-design-considerations-you-need-to-know-about-part-2/index.html
Invoke Lambda AWS SDK Typescript
I wrote my own class to do this, parse the response and check errors. I've posted it here to save anyone else who wants the effort :)
This requires aws-sdk and ts-log.
import { AWSError, Lambda } from 'aws-sdk'
import { Logger } from 'tslog';
export class LambdaClient {
awsLambda: Lambda;
logger: Logger;
constructor(region: string) {
this.awsLambda = new Lambda({ region })
this.logger = new Logger({ name: "LambdaClient" })
}
trigger({ functionName, payload }): Promise<any> {
return new Promise(
(resolve, reject) => {
const params = {
FunctionName: functionName,
InvocationType: 'RequestResponse',
LogType: 'Tail',
Payload: JSON.stringify(payload)
};
this.awsLambda.invoke(params, (err: AWSError, data: Lambda.InvocationResponse) => {
if (err) {
this.logger.error({ message: "error while triggering lambda", errorMessage: err.message })
return reject(err)
}
if (data.StatusCode !== 200 && data.StatusCode !== 201) {
this.logger.error({ message: "expected status code 200 or 201", statusCode: data.StatusCode, logs: base64ToString(data.LogResult) })
return reject(data)
}
const responsePayload = data.Payload
return resolve(JSON.parse(responsePayload.toString()))
})
}
)
}
}
function base64ToString(logs: string) {
try {
return Buffer.from(logs, 'base64').toString('ascii');
} catch {
return "Could not convert."
}
}

Resources