A previous article described the test cases for validating
lambda function handler. This article covers some of the issues encountered and
their resolutions.
First, the version of the lambda runtime might be different
from the development environment. This cascades to version incompatibilities
with the package dependencies for the code invoked. The package-lock.json used
with a nodeJs based lambda function handler articulates the versions expected
for each dependency. Removing the dependencies folder named the ‘node_modules’
folder and refreshing it using the commands “npm install” and “npm audit fix”
will adjust the versions to suit the runtime. Usually, the higher version of
runtime has backward compatibility with the lower versions, so if the lambda
code works with a lower version runtime, it should work with the latest.
A simple lambda code such as the following:
const AWS = require('aws-sdk')
const s3 = new AWS.S3()
exports.handler = async function(event) {
return
s3.listBuckets().promise()
}
Will work on older versions of the runtime.
If we use the Javascript v3 sdk, we might have a syntax as
follows:
// Import required AWS SDK clients and commands for Node.js.
import { ListBucketsCommand } from
"@aws-sdk/client-s3";
import { s3Client } from "./libs/s3Client.js";
export const run = async () => {
try {
const data = await
s3Client.send(new ListBucketsCommand({}));
console.log("Success", data.Buckets);
return data; //
For unit tests.
} catch (err) {
console.log("Error", err);
}
};
And some of the errors encountered might be like “cannot use
import statement outside a module in aws lambda console”. This could be quite a
pesky issue even driving the code to change to using the require syntax. If the
Lambda console allowed using this, it could have alleviated much of the hassle
but there is an easy resolution to this. The package.json could include an
attribute “type”: “module” to denote this is an ECMAScript. There are some
version differences between ECMAScript5 and ECMAScript6 and specifying the
attribute informs the Lambda runtime to use ES modules rather than the
traditional syntax.
It is also better to use configuration layers for nodeJs
modules. These Lambda layers are a convenient way to package dependencies so that
the size of the uploaded deployment archives is reduced. A layer can contain
libraries, a custom runtime, data or configuration files. Layers promote
reusability and separation of responsibilities. Layer contents are archived
into a zip file and uploaded to S3. They are imported under the /opt directory
at execution. If the same folder structure is specified in the layer zip file
archive, the function code can access the content without the need to specify
the path.
No comments:
Post a Comment