overleaf/services/chat/app/js/mongodb.js
Jakob Ackermann 4080784310 [misc] simplify mongodb collection access using a shared db construct
Resolve the getCollection Promises once and store the result in a shared
 `db` object which can get imported by all the call-sites.

The http server is starting only after a Promise of `waitForDb()`
 resolves. This covers the app code and the acceptance tests:
REF: 586706a9439c3591fc9613dc877f055096ca073a
REF: d026569d2eb4123e30c771a55a001b42d5ade72f
2020-09-10 10:08:30 +01:00

25 lines
525 B
JavaScript

const Settings = require('settings-sharelatex')
const { MongoClient, ObjectId } = require('mongodb')
const clientPromise = MongoClient.connect(Settings.mongo.url)
async function getCollection(name) {
return (await clientPromise).db().collection(name)
}
async function waitForDb() {
await clientPromise
}
const db = {}
waitForDb().then(async function () {
db.messages = await getCollection('messages')
db.rooms = await getCollection('rooms')
})
module.exports = {
db,
ObjectId,
getCollection,
waitForDb
}