如何从CDK Context传入邮箱数组并订阅SNS Topic
批量订阅SNS Topic的解决方案(基于CDK Context数组)
问题根源
你直接把字符串数组传给EmailSubscription构造函数,但这个方法只接受单个邮箱字符串,所以触发了类型不匹配的错误。要实现批量订阅,只需要遍历邮箱数组,为每个邮箱单独创建订阅即可。
修改后的完整代码示例
1. 从Context提取并传递到Stack
const app = new cdk.App(); // 提取Context并断言类型,避免ts类型报错 const dlqAlertAddress = app.node.tryGetContext("dlqAlertAddress") as { alertaddress: string[] }; // 创建Stack时把邮箱数组传入props new YourSlackNotificationStack(app, 'SlackNotificationStack', { dlqAlertAddresses: dlqAlertAddress.alertaddress, // 其他必要的props参数... });
2. 在Stack中批量创建订阅
// 遍历邮箱数组,逐个添加SNS订阅 props.dlqAlertAddresses.forEach(email => { slackNotificationEbPipe.dlqTopic.addSubscription( new subscriptions.EmailSubscription(email) ); });
可选优化(处理空数组场景)
如果担心Context里的邮箱数组为空,可以加个判断避免无效执行:
if (props.dlqAlertAddresses?.length) { props.dlqAlertAddresses.forEach(email => { slackNotificationEbPipe.dlqTopic.addSubscription( new subscriptions.EmailSubscription(email) ); }); }
内容的提问来源于stack exchange,提问作者Jatin Mehrotra
相关产品推荐
相关产品推荐

