Reputation: 7541
I'm trying to find the table name to use the dynamo db that is auto generated using AWS Amplify after creating a schema using 'data'. How can I find that?
Here is what I've tried:
resource.ts file
const schema = a
.schema({
UserProfileFlags: a.customType({
isBetaUser: a.boolean(),
isFounder: a.boolean(),
isBanned: a.boolean(),
isSuspended: a.boolean(),
isVerified: a.boolean(),
isDeleted: a.boolean(),
}),
UserProfile: a
.model({
userName: a.string().required(),
owner: a
.string()
.authorization((allow) => [allow.owner().to(['read', 'delete'])]),
...
to define a database in dynamo named UserProfile. That works fine, the db is created and the table exists. Now I'm trying to create a function to access that table. I've tried many iterations, but they all have errors/won't compile or work:
I found this:
import { DynamoDB } from 'aws-sdk';
import { getDataSource } from '@aws-amplify/backend-function';
import type { Schema } from '../../data/resource';
const dynamodb = new DynamoDB.DocumentClient();
export const handler: Schema['createEmptyProfile']['handler'] = async (event, context) => {
const dataSource = getDataSource(context);
const TABLE_NAME = dataSource.resources.UserProfile.tableName;
This one tells me that import { getDataSource } from '@aws-amplify/backend-function';
is a problem:
Module '"@aws-amplify/backend-function"' has no exported member 'getDataSource'.ts(2305)
I've also tried running this: npx ampx generate graphql-client-code --out /graphql
and then
import { env } from "$amplify/env/post-confirmation";
...
endpoint: env.AMPLIFY_DATA_GRAPHQL_ENDPOINT,
...
But this too shows AMPLIFY_DATA_GRAPHQL_ENDPOINT is undefined, and if I look in the generated .ts files, I don't see it either.
That kind of makes sense, since I'm not sure how that would work when deployed, as it needs a different table name. This is all running against a local sandbox.
Here is the docs link that I can find: https://docs.amplify.aws/react/build-a-backend/functions/examples/create-user-profile-record/
Upvotes: 0
Views: 253
Reputation: 1172
You can get the access to the table name (and other details) after defineBackend() is done, like this:
backend.data.resources.tables["UserProfile"].tableName
But in order to use it in your lambda function, add it as env var to the function:
backend.createEmptyProfile.addEnvironment("USER_PROFILE_TABLE", backend.data.resources.tables["UserProfile"].tableName);
And inside the function, just access it with this:
import { env } from "$amplify/env/createEmptyProfile";
const TABLE_NAME = env.USER_PROFILE_TABLE;
NOTE: "env" will be updated locally (so you don't get ts errors) only after you've saved backend.js and run npx ampx sandbox
NOTE2: in order to avoid circular dependency issue when provisioning cloud formation stack, the function needs to belong to the same resource group as the models; for your case I believe this would do it - in the defineFunction() add:
resourceGroupName: "data",
Upvotes: 0