|
| 1 | +const _ = require("lodash"); |
| 2 | +const pEachSeries = require("p-each-series"); |
| 3 | +const fnArgs = require("fn-args"); |
| 4 | +const { promisify } = require("util"); |
| 5 | +const loadMigration = require("../utils/loadMigration"); |
| 6 | + |
| 7 | +module.exports = (config, status) => async db => { |
| 8 | + const statusItems = await status(db, config); |
| 9 | + const pendingItems = _.filter(statusItems, { appliedAt: "PENDING" }); |
| 10 | + const migrated = []; |
| 11 | + |
| 12 | + const migrateItem = async item => { |
| 13 | + try { |
| 14 | + const migration = loadMigration(config.migrationsDir, item.fileName); |
| 15 | + const args = fnArgs(migration.up); |
| 16 | + const up = args.length > 1 ? promisify(migration.up) : migration.up; |
| 17 | + await up(db); |
| 18 | + } catch (err) { |
| 19 | + const error = new Error( |
| 20 | + `Could not migrate up ${item.fileName}: ${err.message}` |
| 21 | + ); |
| 22 | + error.migrated = migrated; |
| 23 | + throw error; |
| 24 | + } |
| 25 | + |
| 26 | + let collectionName; |
| 27 | + if (config.changelogCollectionName) { |
| 28 | + collectionName = config.changelogCollectionName; |
| 29 | + } else { |
| 30 | + collectionName = "changelog"; |
| 31 | + console.warn( |
| 32 | + 'No changelogCollectionName found in confg - defaulting to "changelog"' |
| 33 | + ); |
| 34 | + } |
| 35 | + |
| 36 | + const collection = db.collection(collectionName); |
| 37 | + |
| 38 | + const { fileName } = item; |
| 39 | + const appliedAt = new Date(); |
| 40 | + |
| 41 | + try { |
| 42 | + await collection.insertOne({ fileName, appliedAt }); |
| 43 | + } catch (err) { |
| 44 | + throw new Error(`Could not update changelog: ${err.message}`); |
| 45 | + } |
| 46 | + migrated.push(item.fileName); |
| 47 | + }; |
| 48 | + |
| 49 | + await pEachSeries(pendingItems, migrateItem); |
| 50 | + return migrated; |
| 51 | +}; |
0 commit comments