DynamoDB createTable如果不存在
您需要在DynamoDB上创build一个表。 问题是,如果它存在createTable
响应是一个错误。 我如何避免这一点。 因为我发生错误时会发出通知,但在这种情况下,我不想。
我不想比较错误代码,因为ResourceInUseException
太模糊了。 另外,我不认为先发送一个描述表请求是一个真正的解决scheme。
有没有办法createIfNotExists
?
既然你不喜欢describeTable()那么我猜这个listTables()是你唯一的select,例如
const tableName = // ... const tablePromise = dynamodb.listTables({}) .promise() .then((data) => { const exists = data.TableNames .filter(name => { return name === tableName; }) .length > 0; if (exists) { return Promise.resolve(); } else { const params = { TableName: tableName, // more params }; return dynamodb.createTable(params).promise(); } });
请注意,如果您有超过100个表格,结果将被分页,您必须重复调用listTables()
,有关详细信息,请参阅api文档中的ExclusiveStartTableName
和LastEvaluatedTableName
。
另一个可能的解决scheme可能是检查err.code和err.message。 “err.message”给你的确切原因。
if (err.code === "ResourceInUseException" && err.message === "Cannot create preexisting table") { console.log("message ====>" + err.message); } else { console.error("Unable to create table. Error JSON:", JSON.stringify(err, null, 2)); }