Share connection inside the app - nodejs


#1

Hello,

I’m not sure how to share the connection around my app, for now I have a Couchbase class that is in charge to open the connection:

class CouchBase {
  connect() {
    const self = this;
    if (self.cluster) {
      console.log("DB::connect() already opened.");
      self.bucket = self.cluster.openBucket();
      return Promise.resolve();
    }
    self.cluster = new couchbase.Cluster('couchbase://127.0.0.1');
    self.cluster.authenticate(process.env.DB_USER, process.env.DB_PASSWORD);
    return new Promise((resolve, reject) => {
      self.bucket = self.cluster.openBucket(this.BUCKET_NAME, (err) => {
        if (err) {
          logger.error(`DB::connect() Error: ${JSON.stringify(err)}`);
          reject(err);
        } else {
          self.bucket.operationTimeout = 5000;
          logger.info('DB::connect() OK!');
          resolve(self);
        }
      });
    });
  }
}

then when I start the app I’ll do something like this:

const db = new couchbase();
db.connect()
  .then((_db) => {
    const app = Express();
    app.use('*', (req, res, next) => {
      req.db = _db;
      next();
    })
    ...
    app.listen(5000, () => {
      console.log("Listening at: 5000");
    });
  }).catch((err) => {
    console.log("Error setting up the database connection: ", err);
  });

in this case I can access the db where I have access to the request object…my problem is when I need the db but I’m not able to use the request object…do you have any advice? do I need to change somehting? how can I get the db object wihtout the request? many thanks


#2

Hi @francesco.venica,

Next time, I’d recommend posting node-related questions to the node forum here: https://forums.couchbase.com/c/node-js-sdk

In the meantime, I’m tagging @brett19 as someone who might be able to help answer your question.


#3

There’s a sample application that shows how to wrap this in both in the documentation and at https://github.com/couchbaselabs/try-cb-nodejs


#4

@matthew.groves sure, many thanks!

@ingenthr amazing, now I’'l check this link!

many thanks!