Hi, I am a newbie. How can I create multiple dynam...
# help
a
Hi, I am a newbie. How can I create multiple dynamoDB tables with SST, and how can I pass the name of these tables?
a
a
Would you mind pointing out which section can answer my questions?
a
The table name is auto generated using a combination of stageName, stackName and the provided tableName. So, suppose you create a notes table as per this example -
Copy code
new Table(this, "Notes", {
  fields: {
    userId: TableFieldType.STRING,
    noteId: TableFieldType.STRING,
  },
  primaryIndex: { partitionKey: "noteId", sortKey: "userId" },
});
if your stage name is
dev
, your app name in
sst.json
is
sample-api
and your stack name is
my-stack
then the generated table name would be
dev-sample-api-my-stack-Notes
. This is done to ensure any collisons across other stacks and stages and apps.
a
Thank you for your detailed explanation. So I can create as many tables as I want by creating different Table instances, but how can I refer to these tables later in the API? For example, in the guide
Copy code
this.api = new sst.Api(this, "Api", {
      defaultFunctionProps: {
        environment: {
          TABLE_NAME: table.tableName,
        },
      },
      routes: {
        "POST   /notes": "src/create.main",
      },
    });
it uses
table.tableName
, how can refer to different tables by their names?
a
oh that’s simple.
Copy code
const table1 = new Table(this, "Notes", {
  fields: {
    userId: TableFieldType.STRING,
    noteId: TableFieldType.STRING,
  },
  primaryIndex: { partitionKey: "noteId", sortKey: "userId" },
});

oh that's simple.
const table2 = new Table(this, "Notes2", {
  fields: {
    userId: TableFieldType.STRING,
    noteId: TableFieldType.STRING,
  },
  primaryIndex: { partitionKey: "noteId", sortKey: "userId" },
});

const api = new sst.Api(this, "Api", {
      defaultFunctionProps: {
        environment: {
          NOTES1_TABLE: table1.tableName,
          NOTES2_TABLE: table2.tableName,
        },
      },
      routes: {
        "POST   /notes": "src/create.main",
      },
    });
a
Amazing! Thank you so much ❤️
a
the environment is just a plain object. you can have any string as the key and it can use any string as the value.
sure. have fun.