Search code examples
javascriptnode.jsamazon-web-servicesaws-lambdacassandra

How to make singleton connection in cassandra database in node js


I am using cassandra db so currently every request is creating new connection instance to db. I want if a connection is already establish than skip to create new one. and using a node dependency for connection (cassandra-driver)

Node js 18x

cassendra 3.11.9

cassandra-driver 4.6.4

Current code for create Cassandra connection

 const cassClient = new cassandra.Client({
        contactPoints: ['yourip'],
        pooling: {
          coreConnectionsPerHost: {
            HostDistance:{LOCAL : 2,REMOTE : 1}
          },
          maxRequestsPerConnection: 32768
        },
        localDataCenter: 'ap-south-1',
        keyspace: 'test',
        credentials: { username: 'admin', password: 'admin' }
      });

don't want to create new connection if already a connection is established. want as a singleton pattern connection


Solution

  • A "Singleton" is a simple pattern where you store an instance of an object and your getter create it only if necessary.

    You could implement it like this:

    var cassandraDatabaseManager = (function () {
        var cassClient;
    
        function createInstance() {
            return new cassandra.Client({
            contactPoints: ['yourip'],
            pooling: {
              coreConnectionsPerHost: {
                HostDistance:{LOCAL : 2,REMOTE : 1}
              },
              maxRequestsPerConnection: 32768
            },
            localDataCenter: 'ap-south-1',
            keyspace: 'test',
            credentials: { username: 'admin', password: 'admin' }
          });
        }
    
        return {
            getInstance: function () {
                if (!cassClient) {
                    cassClient= createInstance();
                }
                return cassClient;
            }
        };
    })();
    

    And you can just use it like this:

    const instance = cassandraDatabaseManager.getInstance();