英文:
Simple AWS Lambda question: How to import the AWS SDK in a Lambda function?
问题
Working in the Lambda console, using Node v.18 runtime, and am getting really confused while trying to do some really simple beginner tasks. Specifically, I want to write a Lambda that will be called from API Gateway. This called Lambda will contain / call other lambdas.
Any / all advice is welcome.
Here's some code:
index.mjs:
import AWS from 'aws-sdk'; // <== ERROR HERE
export const handler = async (event) => {
const lambda = new AWS.Lambda();
try {
const fetchFunction = // <== ARN for lambda here. We don't even get this far.
// ... more code to do stuff follows
When I test the Lambda function, it returns an error. Here is the part of the error message that I can't sort out:
"errorMessage": "Cannot find package 'aws-sdk' imported from /var/task/index.mjs\nDid you mean to import aws-sdk/lib/aws.js?",
"trace": [
"Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'aws-sdk' imported from /var/task/index.mjs",
"Did you mean to import aws-sdk/lib/aws.js?",
I've already researched a solution, but the more information I find, the more overwhelming it becomes.
Can anyone suggest a simple work-around / solution? I'm guessing this is really simple but I'm just not seeing a path to a solution.
Thanks in advance,
m
英文:
Working in the Lambda console, using Node v.18 runtime, and am getting really confused while trying to do some really simple beginner tasks. Specifically, I want to write a Lambda that will be called from API Gateway. This called Lambda will contain / call other lambdas.
Any / all advice is welcome.
Here's some code:
index.mjs:
import AWS from 'aws-sdk'; // <== ERROR HERE
export const handler = async (event) => {
const lambda = new AWS.Lambda();
try {
const fetchFunction = // <== ARN for lambda here. We don't even get this far.
// ... more code to do stuff follows
When I test the Lambda function, it returns an error. Here is the part of the error message that I can't sort out:
"errorMessage": "Cannot find package 'aws-sdk' imported from /var/task/index.mjs\nDid you mean to import aws-sdk/lib/aws.js?",
"trace": [
"Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'aws-sdk' imported from /var/task/index.mjs",
"Did you mean to import aws-sdk/lib/aws.js?",
I've already researched a solution, but the more information I find, the more overwhelming it becomes.
Can anyone suggest a simple work-around / solution? I'm guessing this is really simple but I'm just not seeing a path to a solution.
Thanks in advance,
m
答案1
得分: 3
你正在导入v2 SDK。Node 18 lambda运行时仅支持v3 SDK。
https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html
您需要更新您的导入。
import { LambdaClient, InvokeCommand } from '@aws-sdk/client-lambda';
您可以在指南中查看更多语法。https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/preview/client/lambda/command/InvokeCommand/
如果您正在寻找更多示例以帮助入门,我建议查看代码库。它包含了丰富的v3示例集合。
英文:
You're importing the v2 SDK. The node 18 lambda runtime only supports the v3 SDK.
https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html
You'll need to update your imports.
import { LambdaClient, InvokeCommand } from '@aws-sdk/client-lambda';
You can see more of the syntax in the guide. https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/preview/client/lambda/command/InvokeCommand/
If you're looking for more examples to get you started, I would suggest the Code Library. It has a good collection of examples in V3.
答案2
得分: 0
以下是Lambda函数的代码翻译:
// 仅供未来参考,这里是Lambda函数的代码转储。它可能不是完美的结构,但展示了如何在AWS上使用JS SDK v.3 / Node v.18并调用“子Lambda”的基本方法:
**以下是一些代码:**
// 每个Lambda都需要执行IAM权限。
import { LambdaClient, InvokeCommand } from "@aws-sdk/client-lambda";
const asciiDecoder = new TextDecoder('utf-8');
export const handler = async (event) => {
const client = new LambdaClient();
// https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-lambda/classes/invokecommand.html
const fetchParams = {
FunctionName: 'arn:aws:lambda:eu-north-1:880299674189:function:pv-estimate_fetchEstimate', // 必需
// InvocationType: "Event" || "RequestResponse" || "DryRun",
InvocationType: "RequestResponse",
LogType: "Tail",
// ClientContext: "STRING_VALUE",
// Payload: "",
// Qualifier: "STRING_VALUE",
};
const fetchCommand = new InvokeCommand(fetchParams);
try {
let retVal;
let response = await client.send(fetchCommand);
// Payload以数组形式返回。在返回数据之前解码数组并解析为json
const estimate = JSON.parse(asciiDecoder.decode(response.Payload));
const transformParams = {
FunctionName: 'arn:aws:lambda:eu-north-1:880299674189:function:transformRecord', // 必需
InvocationType: "RequestResponse",
LogType: "Tail",
Payload: JSON.stringify(estimate)
};
const transformCommand = new InvokeCommand(transformParams);
response = await client.send(transformCommand);
retVal = JSON.parse(asciiDecoder.decode(response.Payload));
// API Gateway对返回的有效载荷格式要求较高。https://stackoverflow.com/a/43718963/16824901
return {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*", // 跨域支持所需
"Access-Control-Allow-Credentials": true // 与HTTPS一起使用的cookie和授权标头所需
},
body: JSON.stringify(retVal),
};
} catch (error) {
console.error('调用Lambda函数时出错:', error);
return {
statusCode: 500,
body: '调用Lambda函数出错'
};
}
};
希望对您有所帮助。
英文:
Just in case this helps future people, here is a dump of Lambda functions's code. It may not be structured perfectly, but it shows basic approach of what to do, to use JS SDK v.3 / Node v.18 on AWS and invoke "sub Lambdas":
Here is some code:
// Needs lambda execute IAM permission for each lambda, also.
import { LambdaClient, InvokeCommand } from "@aws-sdk/client-lambda";
const asciiDecoder = new TextDecoder('utf-8');
export const handler = async (event) => {
const client = new LambdaClient();
// https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-lambda/classes/invokecommand.html
const fetchParams = {
FunctionName: 'arn:aws:lambda:eu-north-1:880299674189:function:pv-estimate_fetchEstimate', // required
// InvocationType: "Event" || "RequestResponse" || "DryRun",
InvocationType: "RequestResponse",
LogType: "Tail",
// ClientContext: "STRING_VALUE",
// Payload: "",
// Qualifier: "STRING_VALUE",
};
const fetchCommand = new InvokeCommand(fetchParams);
try {
let retVal
let response = await client.send(fetchCommand);
// Payload comes back as array. Decode array and parse as json before returning data
const estimate = JSON.parse(asciiDecoder.decode(response.Payload));
const transformParams = {
FunctionName: 'arn:aws:lambda:eu-north-1:880299674189:function:transformRecord', // required
InvocationType: "RequestResponse",
LogType: "Tail",
Payload: JSON.stringify(estimate)
};
const transformCommand = new InvokeCommand(transformParams);
response = await client.send(transformCommand);
retVal = JSON.parse(asciiDecoder.decode(response.Payload));
// API Gateway is picky about return payload format. https://stackoverflow.com/a/43718963/16824901
return {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*", // Required for CORS support to work
"Access-Control-Allow-Credentials": true // Required for cookies, authorization headers with HTTPS
},
body: JSON.stringify(retVal),
}
}
catch (error) {
console.error('Error invoking Lambda function:', error);
return {
statusCode: 500,
body: 'Error invoking Lambda function'
};
}
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论