I want to create an AWS Amplify Function (Lambda) that can access AWS DataStore objects/models.
I've been having trouble getting it to work. Has anyone successfully gotten this to work, and can provide a code example?
I am able to access DynamoDB directly from the Lambda (I setup all the permissions etc successfully), but I want to access the data through DataStore since that is how my App is accessing and updating data, for data consistency purposes.
The below is more-or-less how my code is (I had to remove confidential stuff) in my index.js file:
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();
}
I get this error when I run this using "amplify mock function function_name":
Error querying DynamoDB or Sending Push: ReferenceError: window is not defined
Thanks, Alex
The AWS-amplify library is designed primarily for use in browser environments, and some of its functionality depends on browser-specific objects like window and document. However, when you're running code in AWS Lambda, you're operating in a server-side environment where these browser-specific objects are not available. To cut a long story short:
windowis not available on server-sideTo interact with AWS DataStore in a server-side environment like AWS Lambda, you can't use the @aws-amplify/datastore package directly as you would in a client-side browser environment. Instead, you would typically interact with the DataStore API using the AWS SDK for JavaScript.