How can I invoke a lambda function using Javascript (TypeScript) aws-sdk v3?
I use the following code which does not seems to work:
// 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.
I see this error message in CloudWatch, not sure if it is relevant to my issue thought:
The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received an instance of Object
Question:
Is the above code to invoke a lambda function correct? or are there any better ways?
As an alternative to the example above, you can avoid using an additional AWS library and use built-in Node function instead Buffer.from.
First import what you need:
import { InvokeCommand, InvokeCommandInput, InvokeCommandOutput } from '@aws-sdk/client-lambda';
Then define your function
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);
}
}
}
Then call it with:
const lambdaService = new LambdaService();
await lambdaService.invokeFunction("name");
If you miss the await, it is possible the function will start executing but never reach the last line.
It looks like your call to lambda.invoke() is throwing a TypeError because the payload that you are passing to it is an object when it needs to be a Uint8Array buffer.
You can modify your code as follows to pass the payload:
// 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)),
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With