Introduction
In this article we will dive deep into AWS Lambda and learn its structure along with its execution. How to have
handler in the function, that AWS Lambda can then invoke when the service executes your code.
- exports.main = function(event, context,) {
-
- }
The callback parameter is optional depending on whether you want to return information to the caller or not.
- exports.main = function(event, context, callback) {
-
- }
Let’s try to understand the syntax:
- event – This parameter is used to pass on the event data to the handler. It can be anything like String, JSON object, etc.
- context – This parameter is used to provide run time information to your lambda function handler. Such as:
- function name (functionName)
- logGroupname (logGroupName)
- logStreamName (logStreamName)
- remainingTime (getRemainingTimeInMillis)
- callback – This optional parameter can be used to return any data back to the caller, or else return value is null
- main – This is the name of the function AWS lambda invokes as seen in the “main” example. It can be named anything like a main, handler, init, etc.
If your code is saved as index.js, then it will be called as index.main, where the index is will be your file name (index.js) and main is the entry point function.
e.g.
- exports.main = function(event, context, callback) {
- console.log("value1 = " + event.key1);
- console.log("value2 = " + event.key2);
- callback(null, "some success message");
- }
As you can see in the above example if function wants to return some data without error, null can be passed in the callback, or else we need to pass an error object in the callback.
The following are different ways callback can be used.
- callback();
- callback(null);
- callback(null, "success");
- callback(error);
There are fewer ways to test and run lambda functions.
- Manually upload a lambda function and test it.
- AWS CLI
- Using AWS API Gateway Endpoint
- Using serverless Infrastructure tools which includes smooth deployment/management/invocation etc.
- Serverless Framework
- Apex
- Chalice
I will try to cover a few of them in a later series.
I hope this article made you understand the code structure of a lambda function and how can it be invoked and managed.