helpers.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. const {
  2. db,
  3. getCollectionNames,
  4. getCollectionInternal,
  5. waitForDb,
  6. } = require('../../app/src/infrastructure/mongodb')
  7. async function addIndexesToCollection(collection, indexes) {
  8. return Promise.all(
  9. indexes.map(index => {
  10. index.background = true
  11. return collection.createIndex(index.key, index)
  12. })
  13. )
  14. }
  15. async function dropIndexesFromCollection(collection, indexes) {
  16. return Promise.all(
  17. indexes.map(async index => {
  18. try {
  19. await collection.dropIndex(index.name)
  20. } catch (err) {
  21. if (err.code === 27 /* IndexNotFound */) {
  22. console.log(`Index ${index.name} not found; drop was a no-op.`)
  23. } else {
  24. throw err
  25. }
  26. }
  27. })
  28. )
  29. }
  30. async function dropCollection(collectionName) {
  31. await waitForDb()
  32. if (db[collectionName]) {
  33. throw new Error(`blocking drop of an active collection: ${collectionName}`)
  34. }
  35. const allCollections = await getCollectionNames()
  36. if (!allCollections.includes(collectionName)) return
  37. const collection = await getCollectionInternal(collectionName)
  38. await collection.drop()
  39. }
  40. module.exports = {
  41. addIndexesToCollection,
  42. dropIndexesFromCollection,
  43. dropCollection,
  44. }