diff --git a/lib/load-migrations.js b/lib/load-migrations.js index 0328fe8..64db324 100644 --- a/lib/load-migrations.js +++ b/lib/load-migrations.js @@ -1,7 +1,7 @@ 'use strict' const path = require('path') -const fs = require('fs') +const fs = require('fs').promises const Migration = require('./migration') module.exports = loadMigrationsIntoSet @@ -22,34 +22,40 @@ function loadMigrationsIntoSet (options, fn) { } // Load from migrations store first up - store.load(function (err, state) { + store.load(async function (err, state) { if (err) return fn(err) - // Set last run date on the set - set.lastRun = state.lastRun || null + try { + // Set last run date on the set + set.lastRun = state.lastRun || null - // Read migrations directory - fs.readdir(migrationsDirectory, function (err, files) { - if (err) return fn(err) + // Read migrations directory + let files = await fs.readdir(migrationsDirectory) // Filter out non-matching files files = files.filter(filterFn) // Create migrations, keep a lookup map for the next step const migMap = {} - let migrations = files.map(function (file) { + const promises = files.map(async function (file) { // Try to load the migrations file + const filepath = path.join(migrationsDirectory, file) let mod try { - mod = require(path.join(migrationsDirectory, file)) + mod = require(filepath) } catch (e) { - return fn(e) + if (e.code === 'ERR_REQUIRE_ESM') { + mod = await import(filepath) + } else { + return fn(e) + } } const migration = new Migration(file, mod.up, mod.down, mod.description) migMap[file] = migration return migration }) + let migrations = await Promise.all(promises) // Fill in timestamp from state, or error if missing state.migrations && state.migrations.forEach(function (m) { @@ -70,6 +76,8 @@ function loadMigrationsIntoSet (options, fn) { // Successfully loaded fn() - }) + } catch (e) { + fn(e) + } }) }