helpers.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // @ts-check
  2. const {
  3. db,
  4. getCollectionNames,
  5. getCollectionInternal,
  6. waitForDb,
  7. } = require('../../app/src/infrastructure/mongodb')
  8. async function addIndexesToCollection(collection, indexes) {
  9. return Promise.all(
  10. indexes.map(index => {
  11. index.background = true
  12. return collection.createIndex(index.key, index)
  13. })
  14. )
  15. }
  16. async function dropIndexesFromCollection(collection, indexes) {
  17. return Promise.all(
  18. indexes.map(async index => {
  19. try {
  20. await collection.dropIndex(index.name)
  21. } catch (err) {
  22. if (err.code === 27 /* IndexNotFound */) {
  23. console.log(`Index ${index.name} not found; drop was a no-op.`)
  24. } else {
  25. throw err
  26. }
  27. }
  28. })
  29. )
  30. }
  31. async function dropCollection(collectionName) {
  32. await waitForDb()
  33. if (db[collectionName]) {
  34. throw new Error(`blocking drop of an active collection: ${collectionName}`)
  35. }
  36. const allCollections = await getCollectionNames()
  37. if (!allCollections.includes(collectionName)) return
  38. const collection = await getCollectionInternal(collectionName)
  39. await collection.drop()
  40. }
  41. /**
  42. * Asserts that a dependent migration has run. Throws an error otherwise.
  43. *
  44. * @param {string} migrationName
  45. */
  46. async function assertDependency(migrationName) {
  47. await waitForDb()
  48. const migrations = await getCollectionInternal('migrations')
  49. const migration = await migrations.findOne({ name: migrationName })
  50. if (migration == null) {
  51. throw new Error(
  52. `Bad migration order: ${migrationName} should run before this migration`
  53. )
  54. }
  55. }
  56. module.exports = {
  57. addIndexesToCollection,
  58. dropIndexesFromCollection,
  59. dropCollection,
  60. assertDependency,
  61. }