How do I use AWS Amplify tables from an API Gateway Lambda?

Viewed 138

I had an HTTP API built using the AWS API Gateway. Then I designed an admin web interface for the API using AWS Amplify.

The two systems communicate only through DynamoDB tables: the API writes to a table, the web interface reads from it.

For the sake of DRY the tables are created in Amplify from a GraphQL schema and not by CloudFormation resources with explicit table names. This way there's no need to define the tables in 2 places.

But now I have a problem: the Amplify tables come with random names such as foo-55c3wkhfdhj-bar, so to write to them from an AWS Lambda I need a way to know the name or its random part.

How do I do that? I know about the CloudFormation export mechanism. Can I use it?

Now I have a simple solution of hardcoding the table names in a configuration file such as

{ foo: "foo-55c3wkhfdhj-bar" }

Are there better solutions?

Note that I like the ApiGateway service the way it is. I don't want to move the lambdas into the Amplify backend. Imagine that it wasn't APIGateway but some code that cannot be easily migrated to AWS Lambda backend, say EC2.

https://github.com/aws-amplify/amplify-cli/issues/996 has some ideas, but creating a table elsewhere and using it in the AWS Amplify part is exactly what I want to avoid. And unlike there I don't care if Amplify names are random or not.

1 Answers

I've solved this exact issue in a bash script using the aws cli:

aws dynamodb list-tables --output text | sed -n "s/^.*\($TABLE_NAME-.*-$ENV\)[.\n]*/\1/p"

The variable $TABLE_NAME is the predictable prefix of the table and $ENV is the amplify environment suffix.

Then fancy sed command uses regex to capture the full table name using a capture group so that the full table name is the only thing that comes out.

You could probably do something similar with the AWS API:

https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_ListTables.html

Ping the api to get a list of the tables and the parse and sort them to find the table you're looking for.

Related