Reputation: 4481
I'm building a Serverless application using NodeJS and using MongoDB. I noticed that a lot of connections are created when handling a request. So I came up with a caching mechanism but it doesn't seem to be working. Here is my code.
Connection file
'use strict';
const connectDatabase = mongoClient => mongoClient.connect(process.env.MONGODB_STRING, { poolSize: 10 });
const createConnection = (mongoClient, dbConnection) => {
return new Promise(async (resolve, reject) => {
try {
if (dbConnection) {
console.log('===== Cached Connection =====');
resolve(dbConnection);
}
console.log('===== New Connection =====');
let dbPool = await connectDatabase(mongoClient);
resolve(dbPool);
} catch (error) {
reject(error);
}
});
};
const closeDbConnection = conn => {
if (conn) {
return conn.close();
}
};
module.exports = {
connectDatabase: connectDatabase,
createConnection: createConnection,
closeDbConnection: closeDbConnection
};
Handler code
let admin = require('./lib/admin');
let helper = require('./lib/helper');
let connection = require('./lib/connection');
let mongo = require('mongodb');
let mongoClient = mongo.MongoClient;
let cachedDb = null;
let createUser = async (event, context, callback) => {
context.callbackWaitsForEmptyEventLoop = false;
cachedDb = await connection.createConnection(mongoClient, cachedDb);
admin.createUser(cachedDb, helper.parseEvent(event), callback);
};
I'm using a global variable cachedDb
to store the database connection but
each and every time I make a request it logs ===== New Connection =====
any idea how to achieve this.
Is there a better way to handle this?.
Upvotes: 2
Views: 1957
Reputation: 210
The approach I like using here is a singleton class, like this:
export default class MyMongoConnection {
static instance;
static getInstance() {
if (!MyMongoConnection.instance) {
MyMongoConnection.instance = MyMongoConnection.createInstance();
}
return MyMongoConnection.instance;
}
static createInstance() {
// Do whatever you need to create the instance
}
}
So you import MyMongoConnection anywhere and just ask for the instance using .getInstance(), if it exists, it reuses it.
Hope this helps.
Upvotes: 3