如何在 aws-sdk v3 中调用 lambda 函数

A-S*_*ani 7 javascript node.js typescript aws-lambda aws-sdk-js

如何使用 Javascript (TypeScript) aws-sdk v3 调用 lambda 函数?

我使用以下代码似乎不起作用:

// the payload (input) to the "my-lambda-func" is a JSON as follows:
const input = {
    name: 'fake-name',
    serial: 'fake-serial',
    userId: 'fake-user-id'
};

// Payload of InvokeCommandInput is of type Uint8Array
const params: InvokeCommandInput = {
    FunctionName: 'my-lambda-func-name',
    InvocationType: 'RequestResponse',
    LogType: 'Tail',
    Payload: input as unknown as Uint8Array, // <---- payload is of type Uint8Array
  };
  
  console.log('params: ', params); // <---- so far so good.
  const result = await lambda.invoke(params);
  console.log('result: ', result); // <---- it never gets to this line for some reason.
Run Code Online (Sandbox Code Playgroud)

我在 CloudWatch 中看到此错误消息,不确定它是否与我的问题想法相关:

第一个参数必须是字符串类型或者 Buffer、ArrayBuffer、Array 或类数组对象的实例。收到一个Object实例

问题:

上面调用 lambda 函数的代码正确吗?或者还有什么更好的方法吗?

Mat*_*ner 10

作为上述示例的替代方案,您可以避免使用额外的 AWS 库并使用内置 Node 函数而不是 Buffer.from。

首先导入你需要的东西:

import { InvokeCommand, InvokeCommandInput, InvokeCommandOutput } from '@aws-sdk/client-lambda';
Run Code Online (Sandbox Code Playgroud)

然后定义你的函数

export class LambdaService {    
    async invokeFunction(name: string): Promise<void> {
        try {
            const payload = { name: name };

            const input: InvokeCommandInput = {
                FunctionName: "my-lambda-func-name", 
                InvocationType: "Event", 
                Payload: Buffer.from(JSON.stringify(payload), "utf8"),
            };
        
            const command = new InvokeCommand(input);

            const res : InvokeCommandOutput = await lambdaClient.send(command);
        } catch (e) {
            logger.error("error triggering function", e as Error);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后用以下方式调用它:

const lambdaService = new LambdaService();
await lambdaService.invokeFunction("name");
Run Code Online (Sandbox Code Playgroud)

如果您错过了等待,该函数可能会开始执行但永远不会到达最后一行。


jar*_*mod 6

看起来您的调用lambda.invoke()抛出了 TypeError,因为当您传递给它的有效负载需要是 Uint8Array 缓冲区时,它是一个对象。

您可以按如下方式修改代码以传递有效负载:

// import { fromUtf8 } from "@aws-sdk/util-utf8-node";

const { fromUtf8 } = require("@aws-sdk/util-utf8-node");

// the payload (input) to the "my-lambda-func" is a JSON as follows:
const input = {
  name: 'fake-name',
  serial: 'fake-serial',
  userId: 'fake-user-id'
};

// Payload of InvokeCommandInput is of type Uint8Array
const params: InvokeCommandInput = {
  FunctionName: 'my-lambda-func-name',
  InvocationType: 'RequestResponse',
  LogType: 'Tail',
  Payload: fromUtf8(JSON.stringify(input)),
};
Run Code Online (Sandbox Code Playgroud)