Write a class in TypeScript for a basic Node.js Lambda function.
TypeScriptIn AWS, Lambda is a serverless computing service that runs your code in response to events and automatically manages the computing resources for you.
Here's how to create a class for a basic Node.js Lambda function with Pulumi and TypeScript.
Using the
aws.lambda.Function
class, we can provide thecode
andhandler
properties to define our Node.js function.In our case, our Lambda will simply return a "Hello, World!" message when it gets triggered.
import * as pulumi from "@pulumi/pulumi"; import * as aws from "@pulumi/aws"; class MyLambda { lambdaFunction: aws.lambda.Function; constructor(name: string) { // Create an AWS resource (of type Lambda Function) this.lambdaFunction = new aws.lambda.Function(name, { runtime: aws.lambda.NodeJS12dXRuntime, // Use Node.js 12.x as the runtime. code: new pulumi.asset.AssetArchive({ "index.js": new pulumi.asset.StringAsset('exports.handler = function(event, context, callback) { callback(null, "Hello, World!"); };'), }), handler: "index.handler", // Specify the file and exported handler function. }); } } // Exporting a new instance of the class with a unique name 'my-lambda-function' export const myFunc = new MyLambda('my-lambda-function');
In this
MyLambda
class, the constructor takes aname
and generates a Lambda function with that name. This function, when triggered, executes the code defined within thecode
attribute, specifically the exported function inindex.js
. The code contained within the handler function is a simple "Hello, World!" message sender in Node.js.This lambda function doesn't do anything beyond sending a static "Hello, World!" message, so you would typically replace the function body with your own business logic. You could also parameterize this class further to take in the handler function code, the runtime, and other configuration settings as constructor arguments, depending on your use case.