2024-05-02 08:42:48 -04:00
|
|
|
// @ts-check
|
|
|
|
|
2024-10-02 05:32:13 -04:00
|
|
|
import mongodb from '../../app/src/infrastructure/mongodb.js'
|
|
|
|
const { db, getCollectionNames, getCollectionInternal, waitForDb } = mongodb
|
2021-07-21 06:34:09 -04:00
|
|
|
|
|
|
|
async function addIndexesToCollection(collection, indexes) {
|
|
|
|
return Promise.all(
|
|
|
|
indexes.map(index => {
|
|
|
|
index.background = true
|
|
|
|
return collection.createIndex(index.key, index)
|
|
|
|
})
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
async function dropIndexesFromCollection(collection, indexes) {
|
2022-06-30 05:27:32 -04:00
|
|
|
return Promise.all(
|
|
|
|
indexes.map(async index => {
|
|
|
|
try {
|
|
|
|
await collection.dropIndex(index.name)
|
|
|
|
} catch (err) {
|
|
|
|
if (err.code === 27 /* IndexNotFound */) {
|
|
|
|
console.log(`Index ${index.name} not found; drop was a no-op.`)
|
|
|
|
} else {
|
|
|
|
throw err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
)
|
2021-07-21 06:34:09 -04:00
|
|
|
}
|
|
|
|
|
2022-01-10 06:36:18 -05:00
|
|
|
async function dropCollection(collectionName) {
|
|
|
|
await waitForDb()
|
|
|
|
if (db[collectionName]) {
|
|
|
|
throw new Error(`blocking drop of an active collection: ${collectionName}`)
|
|
|
|
}
|
|
|
|
|
2021-07-21 06:34:09 -04:00
|
|
|
const allCollections = await getCollectionNames()
|
|
|
|
if (!allCollections.includes(collectionName)) return
|
2022-01-10 06:36:18 -05:00
|
|
|
const collection = await getCollectionInternal(collectionName)
|
|
|
|
await collection.drop()
|
2021-07-21 06:34:09 -04:00
|
|
|
}
|
|
|
|
|
2024-05-02 08:42:48 -04:00
|
|
|
/**
|
|
|
|
* Asserts that a dependent migration has run. Throws an error otherwise.
|
|
|
|
*
|
|
|
|
* @param {string} migrationName
|
|
|
|
*/
|
|
|
|
async function assertDependency(migrationName) {
|
|
|
|
await waitForDb()
|
|
|
|
const migrations = await getCollectionInternal('migrations')
|
|
|
|
const migration = await migrations.findOne({ name: migrationName })
|
|
|
|
if (migration == null) {
|
|
|
|
throw new Error(
|
|
|
|
`Bad migration order: ${migrationName} should run before this migration`
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-10-02 05:32:13 -04:00
|
|
|
export default {
|
2021-07-21 06:34:09 -04:00
|
|
|
addIndexesToCollection,
|
|
|
|
dropIndexesFromCollection,
|
|
|
|
dropCollection,
|
2024-05-02 08:42:48 -04:00
|
|
|
assertDependency,
|
2021-07-21 06:34:09 -04:00
|
|
|
}
|