helpers.mjs 1.7 KB

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