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