在我的 NextJS v14 项目中,我想在每次用户注册时创建一个 Dynamo 数据库记录。因此,我遵循了这个官方 AWS 教程,但我偶然发现了一些问题,例如:
当我运行
amplify update function
以允许对我的函数进行Mutation
操作时,最后我只得到:
You can access the following resource attributes as environment variables from your Lambda function:
API_<MY_API_NAME>_GRAPHQLAPIENDPOINTOUTPUT
API_<MY_API_NAME>_GRAPHQLAPIIDOUTPUT
同时,我希望稍后能在我的 lambda 函数中使用它(如指南中所示)
API_<MY_API_NAME>_GRAPHQLAPIKEYOUTPUT
文件:
custom.js
与本教程的唯一区别是,我没有使用
const GRAPHQL_ENDPOINT = process.env.API_<MY_API_NAME>_GRAPHQLAPIENDPOINTOUTPUT;
const GRAPHQL_API_KEY = process.env.API_<MY_API_NAME>_GRAPHQLAPIIDOUTPUT;
const query = /* GraphQL */ `
mutation CREATE_USER($input: CreateUserInput!) {
createUser(input: $input) {
username
email
mobilePhoneNumber
}
}
`;
/**
* @type {import('@types/aws-lambda').APIGatewayProxyHandler}
*/
export const handler = async (event, context) => {
const variables = {
input: {
username: event.userName,
email: event.request.userAttributes.email,
mobilePhoneNumber: event.request.userAttributes.phone_number,
},
};
const options = {
method: "POST",
headers: {
"x-api-key": GRAPHQL_API_KEY,
"Content-Type": "application/json",
},
body: JSON.stringify({ query, variables }),
};
const response = {};
try {
const res = fetch(GRAPHQL_ENDPOINT, options);
response.data = await res.json();
if (response.data.errors) response.statusCode = 400;
} catch (error) {
response.statusCode = 400;
response.body = {
errors: [
{
message: error.message,
stack: error.stack,
},
],
};
}
return {
...response,
body: JSON.stringify(response.body),
};
};
模块,而是使用
native获取函数,因为我使用的是 Node v18(如 此官方 AWS Amplify 文档 中所建议的那样,并由线
node-fetch
位于 "Runtime": "nodejs18.x"
)之内但是当调用这个 lambda 函数时,我收到此错误:
/amplify/backend/function/<my_function_name>/...-cloudformation-template.json
现在,正如您所见,我没有使用任何
{
"errorType": "ReferenceError",
"errorMessage": "require is not defined in ES module scope, you can use import instead\nThis file is being treated as an ES module because it has a '.js' file extension and '/var/task/package.json' contains \"type\": \"module\". To treat it as a CommonJS script, rename it to use the '.cjs' file extension."
}
导入,但我发现
自动生成的require
文件(内部:index.js
)有这一行:/amplify/backend/function/<my_function_name>/src/index.js
而且我不太确定 - 也因为我对 AWS 有点陌生 - 是否允许我手动编辑此文件以使其与 ESM 兼容。
/**
* The array of imported modules.
*/
const modules = moduleNames.map((name) => require(`./${name}`));
:
package.json
{
"name": "...",
"type": "module",
"version": "2.0.0",
"description": "Lambda function generated by Amplify",
"main": "index.js",
"license": "Apache-2.0",
"devDependencies": {
"@types/aws-lambda": "^8.10.92"
}
}
中将
package.json
更改为 "type": "module",