https://serverless-stack.com/ logo
#help
Title
# help
a

Adrian Schweizer

11/03/2021, 1:15 AM
is there a best practice how to transport table names created from storage stacks to lambdas that have to access them? I haven't found a solution yet that I'm satisfied with...
m

Michael Clifford

11/03/2021, 1:49 AM
a

Adrian Schweizer

11/03/2021, 8:25 PM
No, i mean, in the lambda function, you do something like:
Copy code
const client = new AWS.DynamoDB.DocumentClient();
client.query({
      TableName: // Needs cdk generated table name here,
      // other query options
   });
i can stuff the table names through process env somehow, but I was just wondering how you guys do it and if there is a better way
if you only have 1 table it's no big deal, but it becomes a bit unwieldy if you have dozens of tables to stuff every name down into process env vars
m

Michael Clifford

11/03/2021, 8:28 PM
@Adrian Schweizer right, is the table created in a stack in the same repo?
if so, you can pass it in as a prop via https://github.com/cliffom/sst-bff-demo/blob/main/stacks/index.ts#L32 However to your point, with lots of tables it gets unwieldly
a

Adrian Schweizer

11/03/2021, 9:05 PM
yeah, it's what I'm doing, but it's a bit tedious
i think i'm gonna store the tables in a map and use the keys as env var names and then do
app.addDefaultFunctionEnv
to add them all in one swoop
Doesn't work. When I try this in index.js:
Copy code
const storageStack = new StorageStack(app, "storage");

   // Add table names to process environment for lambda functions
   const tableNames = {};
   Object.keys(storageStack.tables).forEach((key) => {
      const name = 'TABLE_NAME_' + key.toUpperCase();
      tableNames[name] = storageStack.tables[key].tableName;
   });
   console.log(tableNames);
   app.addDefaultFunctionEnv(tableNames);
it fails to deploy the storage stack
here is output of tableNames:
Copy code
{
  TABLE_NAME_USERS: '${Token[TOKEN.185]}',
  TABLE_NAME_ORGANISATIONS: '${Token[TOKEN.192]}',
  TABLE_NAME_EVENTS: '${Token[TOKEN.199]}',
  TABLE_NAME_PARTICIPATIONS: '${Token[TOKEN.206]}'
}
it is the line
app.addDefaultFunctionEnv(tableNames);
if I remove it, deployment works again
i'm going to make a new thread, as this is only slightly related to the original question