Hello guys! Question! How can I reference one stac...
# sst
b
Hello guys! Question! How can I reference one stack in another stack? In your example, you create DynamoDB Stack + the API in the same file. But what if I want to create a separate file, one for DynamoDB and one for the API, then allow the API to access the DynamoDB(my table) in my API file.
Do I have to do something like this?
export default function main(app) {
const table = new DynamoDB(app, "dynamodb");
new MyApi(app, "MyAPI", { table });
}
d
You can pass stack's
this
object. It's code, so passing around references are fine.
b
I wondered if it’s the best practice. This what I did for information. Thx @Dennis Dang DynamoStack; 
export default class DynamoDB extends sst.Stack {
 
constructor(scope, id, props) {
  
super(scope, id, props);
  
this.table = new sst.Table(this, "xxx", {
   
fields: {
    
PK: sst.TableFieldType.STRING,
    
SK: sst.TableFieldType.STRING,
   
},
   
primaryIndex: { partitionKey: "PK", sortKey: "SK" },
  
});
 
}
}
MyApi; 
export default class MyApi extends sst.Stack {
 
constructor(scope, id, props) {
  
super(scope, id, props);
  
const { table } = props;
  
const api = new sst.Api(this, "Api", {
   
routes: {
    
"POST /projects": "src/project/create.main",
   
},
  
});
  
api.attachPermissions([table]);
 
}
}
App file
export default function main(app) {
 
const { table } = new DynamoDB(app, "dynamodb");
 
new Cognito(app, "cognito-auth-service");
 
new ProjectAPI(app, "api-project-service", { table });
}
d
That looks good to me. I believe CDK is still so new that there's no best practice. Even if you peruse all the cdk examples from the aws-examples repo, they're almost all very simple, and provide little abstraction to help organize code. But in principle, we're mutating this giant stack object that gets transformed into cloudformation.
f
@Bma that’s what I would do too. In this case CDK auto-creates a stack output of the table’s ARN (b/c that’s what’s being used by the attachPermissions call in the API stack) in the DynamoDB stack and the exports it. And the API stack auto-imports the it.