inside
inside

Reputation: 3177

Invoke amazon lambda function from node app

I am going through a basic AWS on how to create a lambda function: Using AWS Lambda with Amazon S3

In this example we are creating an image re-sizing service, one way to trigger it is to listen for some image to be pushed to a S3 bucket and then lambda function will be executed.

But I am trying to understand how to invoke this lambda function from my nodejs app, when user send an image to my node server, I send this image to aws lambda via REST API to be re-sized and then receive the new image location as a response.

Is there any kind of example I can follow? I am more interested in the actual invocation part, since I already have my lambda service up and running.

Thanks

Upvotes: 41

Views: 45341

Answers (4)

user358041
user358041

Reputation: 165

Update for AWS SDK v3

Similar to the docs and Isaac's answer, just including imports to avoid confusion between AWS SDK v2 and v3.

import { InvokeCommand, LambdaClient, LogType } from "@aws-sdk/client-lambda";

async function executeMyLambda() {
  const client = new LambdaClient({ region: "YOURREGION" });
  const command = new InvokeCommand({
    FunctionName: "YOURLAMBDANAME",
    Payload: JSON.stringify(YOURJSONINPUTOBJECT),
    LogType: LogType.Tail,
  });

  const { Payload, LogResult } = await client.send(command);
  const result = Buffer.from(Payload).toString();
  const logs = Buffer.from(LogResult, "base64").toString();
}

Upvotes: 2

Isaac Sichangi
Isaac Sichangi

Reputation: 75

2023 Update

You can invoke a Lambda function by using the AWS JavaScript SDK

  let bucketRegion = "AWS_BUCKET_REGION";
            let IdentityPoolId = "IDENTITY_POOLID";

            AWS.config.update({
                region: bucketRegion,
                credentials: new AWS.CognitoIdentityCredentials({
                    IdentityPoolId: IdentityPoolId
                })
            });
            let lambda = new AWS.Lambda();

            let params = {
                FunctionName: 'LAMBDA_FUNCTION_NAME', /* required */
                Payload: JSON.stringify( {
                        parameter1: value,
                        parameter2: value


                })
            };

            lambda.invoke(params,  function (err, data){
                if (err) {
                    // an error occurred
                    

                }else{
                    // successful response
                    console.log('Success, payload', data);
                   
                }
            });



       
   


Upvotes: -1

sdgfsdh
sdgfsdh

Reputation: 37101

Here is an answer that is more idomatic for the latest JavaScript.

import AWS from 'aws-sdk';

const invokeLambda = (lambda, params) => new Promise((resolve, reject) => {
  lambda.invoke(params, (error, data) => {
    if (error) {
      reject(error);
    } else {
      resolve(data);
    }
  });
});

const main = async () => {

  // You shouldn't hard-code your keys in production! 
  // http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-configuring.html
  AWS.config.update({ 
    accessKeyId: 'AWSAccessKeyId', 
    secretAccessKey: 'AWSAccessKeySecret', 
    region: 'eu-west-1',
  });

  const lambda = new AWS.Lambda();

  const params = {
    FunctionName: 'my-lambda-function', 
    Payload: JSON.stringify({
      'x': 1, 
      'y': 2,
      'z': 3,
    }),
  };

  const result = await invokeLambda(lambda, params);

  console.log('Success!');
  console.log(result);
};

main().catch(error => console.error(error));

Update

Rejoice! The AWS SDK now supports promises:

import AWS from 'aws-sdk';

const main = async () => {

  // You shouldn't hard-code your keys in production! 
  // http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-configuring.html
  AWS.config.update({ 
    accessKeyId: 'AWSAccessKeyId', 
    secretAccessKey: 'AWSAccessKeySecret', 
    region: 'eu-west-1',
  });

  const params = {
    FunctionName: 'my-lambda-function', 
    Payload: JSON.stringify({
      'x': 1, 
      'y': 2,
      'z': 3,
    }),
  };

  const result = await (new AWS.Lambda().invoke(params).promise());

  console.log('Success!');
  console.log(result);
};

main().catch(error => console.error(error));

Upvotes: 41

Ryan
Ryan

Reputation: 5983

Since you are using a node.js server you can just invoke your lambda directly with the AWS JavaScript SDK(https://www.npmjs.com/package/aws-sdk). This way you don't have to worry about using API Gateway.

Invoking from your server is as simple as:

var AWS = require('aws-sdk');

// you shouldn't hardcode your keys in production! See http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-configuring.html
AWS.config.update({accessKeyId: 'akid', secretAccessKey: 'secret'});

var lambda = new AWS.Lambda();
var params = {
  FunctionName: 'myImageProcessingLambdaFn', /* required */
  Payload: PAYLOAD_AS_A_STRING
};
lambda.invoke(params, function(err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else     console.log(data);           // successful response
});

See the rest of the SDK docs here: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Lambda.html

Upvotes: 69

Related Questions