Jack
Jack

Reputation: 377

How to fix the 'duplicate database object for the same connection' dynamodb warning

I have a lambda running using nodejs and dynamoDB and I can see the following log in cloudwatch, I'm not sure how to resolve this?

undefined WARN WARNING: Creating a duplicate database object for the same connection.

the code inside the lambda uses the following

const dynamoDbClient = new DynamoDb(config.dynamoDb, logger);


interface dynamoDB {
{
  region: string;
  endpoint?: string;
  accessKeyId?: string;
  secretAccessKey?: string;
  convertEmptyValues?: boolean;
}

The code that queries dynamodb and uses the connection is included below

new AWS.DynamoDB.DocumentClient(this.config).put(..)

Upvotes: 1

Views: 2388

Answers (1)

Mrk Fldig
Mrk Fldig

Reputation: 4496

My guess would be you're not checking if you already have a connection, so my MySQL class looks like this:

export default class MySQL {
  constructor() {
    this.connection = null;
  }

  to() {

    return promise.then((data) => {
        return [null, data]
    }).catch(err => [err])
  }

  async getConnection() {
    if (this.connection === null || this.connection.state === 'disconnected') {
      return this.createConnection();
    }

    return this.connection;
  }

  async createConnection() {
    this.connection = await mysql.createConnection({
      host: 'dbhost',
      user: 'user',
      password: 'password',
      database: 'db',
    });


    return this.connection;
  }

  async query(sql, params) {
    await this.getConnection();

    let err;
    let rows;
    [err, rows] = await this.to(this.connection.query(sql, params));

    if (err) {
      console.log(err);
      return false;
    }

    return rows;
  }
}

So on query, it checks if it's a reused lambda container and creates a connection if it's not.

Upvotes: 3

Related Questions