mongodb.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // @ts-check
  2. const Metrics = require('@overleaf/metrics')
  3. const MongoUtils = require('@overleaf/mongo-utils')
  4. const Settings = require('@overleaf/settings')
  5. const { MongoClient, ObjectId, ReadPreference } = require('mongodb-legacy')
  6. const READ_PREFERENCE_SECONDARY = Settings.mongo.hasSecondaries
  7. ? ReadPreference.secondary.mode
  8. : ReadPreference.secondaryPreferred.mode
  9. const mongoClient = new MongoClient(Settings.mongo.url, Settings.mongo.options)
  10. const mongoDb = mongoClient.db()
  11. const db = {
  12. docs: mongoDb.collection('docs'),
  13. docSnapshots: mongoDb.collection('docSnapshots'),
  14. projects: mongoDb.collection('projects'),
  15. }
  16. async function healthCheck() {
  17. const res = await mongoDb.command({ ping: 1 })
  18. if (!res.ok) {
  19. throw new Error('failed mongo ping')
  20. }
  21. }
  22. Metrics.mongodb.monitor(mongoClient)
  23. async function cleanupTestDatabase() {
  24. await MongoUtils.cleanupTestDatabase(mongoClient)
  25. }
  26. module.exports = {
  27. db,
  28. ObjectId,
  29. mongoClient,
  30. healthCheck: require('node:util').callbackify(healthCheck),
  31. cleanupTestDatabase,
  32. READ_PREFERENCE_SECONDARY,
  33. }