DynamoDB createTable if not exists

14,353

Solution 1

Since you don't like describeTable() then I guess that listTables() is your only option, e.g.

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();
        }
    });

Note, if you have more than 100 tables, the result will be paged and you must call listTables() repeatedly, see ExclusiveStartTableName and LastEvaluatedTableName in the api docs for details.

Solution 2

One other possible solution could be to check the err.code and err.message. The "err.message" gives you the exact reason.

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)); 
    }
Share:
14,353
Dushyant Bangal
Author by

Dushyant Bangal

Updated on June 19, 2022

Comments

  • Dushyant Bangal
    Dushyant Bangal almost 2 years

    Hi need to create a table on DynamoDB. The problem is, if it exists createTable response is an error. How do i avoid that. Because I throw a notification when error occurs, but in this case, I don't want to.

    I don't want to compare the error code because ResourceInUseException is too vague for it. Also, I don't think sending a describe table request first is really a proper solution.

    Is there any way to createIfNotExists?

  • Dushyant Bangal
    Dushyant Bangal almost 8 years
    Well, I'm already doing that. Sorry i should've mentioned it. The problem is, it might break if they change the string. Like ResourceInUseException to ResourceAlreadyExistsException