diff --git a/apps/meteor/ee/server/services/authorization/service.ts b/apps/meteor/ee/server/services/authorization/service.ts index a983dd5a0e86..3cad2245f557 100644 --- a/apps/meteor/ee/server/services/authorization/service.ts +++ b/apps/meteor/ee/server/services/authorization/service.ts @@ -4,9 +4,6 @@ import { api } from '../../../../server/sdk/api'; import { Authorization } from '../../../../server/services/authorization/service'; import { getConnection } from '../mongo'; -getConnection() - .then((db) => api.registerService(new Authorization(db))) - .catch((error) => { - console.error(error); - process.exit(1); - }); +getConnection().then((db) => { + api.registerService(new Authorization(db)); +}); diff --git a/apps/meteor/ee/server/services/mongo.ts b/apps/meteor/ee/server/services/mongo.ts index ff21fdc20b1a..d96b0a75f77d 100644 --- a/apps/meteor/ee/server/services/mongo.ts +++ b/apps/meteor/ee/server/services/mongo.ts @@ -1,4 +1,5 @@ -import { MongoClient, Db, Collection } from 'mongodb'; +import { MongoClient } from 'mongodb'; +import type { Db, Collection } from 'mongodb'; const { MONGO_URL = 'mongodb://localhost:27017/rocketchat' } = process.env; @@ -14,23 +15,43 @@ export enum Collections { Settings = 'rocketchat_settings', } -let db: Db; -export async function getConnection(poolSize = 5): Promise { - if (!db) { - const client = new MongoClient(MONGO_URL, { - useUnifiedTopology: true, - useNewUrlParser: true, - poolSize, - }); - - await client.connect(); - db = client.db(name); - } +function connectDb(poolSize: number): Promise { + const client = new MongoClient(MONGO_URL, { + useUnifiedTopology: true, + useNewUrlParser: true, + poolSize, + }); - return db; + return client.connect().catch((error) => { + // exits the process in case of any error + console.error(error); + process.exit(1); + }); } +let db: Db; + +export const getConnection = ((): ((poolSize?: number) => Promise) => { + let client: Promise; + + return async (poolSize = 5): Promise => { + if (db) { + return db; + } + if (!client) { + client = connectDb(poolSize); + client.then((c) => { + db = c.db(name); + }); + } + // if getConnection was called multiple times before it was connected, wait for the connection + return (await client).db(name); + }; +})(); + export async function getCollection(name: Collections): Promise> { - await getConnection(); + if (!db) { + db = await getConnection(); + } return db.collection(name); }