Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DynamoDB createTable if not exists

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?

like image 299
Dushyant Bangal Avatar asked May 19 '16 17:05

Dushyant Bangal


2 Answers

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.

like image 179
matsev Avatar answered Sep 22 '22 16:09

matsev


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)); 
    }
like image 27
notionquest Avatar answered Sep 19 '22 16:09

notionquest