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?
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)),
};