我想创建一个可以访问 AWS DataStore 对象/模型的 AWS Amplify 函数 (Lambda)。
我一直无法让它发挥作用。有没有人成功地让它工作,并且可以提供代码示例?
我可以直接从 Lambda 访问 DynamoDB(我成功设置了所有权限等),但我想通过 DataStore 访问数据,因为这就是我的应用程序访问和更新数据的方式,以实现数据一致性。
下面是我的 index.js 文件中的代码的大致情况(我必须删除机密内容):
const { Amplify } = require('aws-amplify');
const { DataStore } = require('@aws-amplify/datastore');
const { Devices } = require('./models');
// Configure Amplify without browser-specific settings
Amplify.configure({
aws_project_region: '(removed...)',
aws_cognito_identity_pool_id: '(removed...)',
aws_cognito_region: '(removed...)',
aws_user_pools_id: '(removed...)',
aws_user_pools_web_client_id: '(removed...)',
});
/**
* @type {import('@types/aws-lambda').APIGatewayProxyHandler}
*/
exports.handler = async (event) => {
console.log(`EVENT: ${JSON.stringify(event)}`);
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Promise Rejection:', reason);
});
// this does not work
await DataStore.start();
const items = await DataStore.query(Devices); // my tablename in DataStore
console.log('Devices DataStore query results: ' + JSON.stringify(items));
await DataStore.stop();
}
当我使用“放大模拟函数 function_name”运行此命令时,出现此错误:
Error querying DynamoDB or Sending Push: ReferenceError: window is not defined
谢谢, 亚历克斯
AWS-amplify 库主要设计用于浏览器环境,其某些功能取决于特定于浏览器的对象,例如窗口和文档。但是,当您在 AWS Lambda 中运行代码时,您是在服务器端环境中操作,这些特定于浏览器的对象不可用。 长话短说:
window
在服务器端不可用
要在 AWS Lambda 等服务器端环境中与 AWS DataStore 交互,您不能像在客户端浏览器环境中那样直接使用 @aws-amplify/datastore 包。相反,您通常会使用适用于 JavaScript 的 AWS 开发工具包与 DataStore API 进行交互。