Skip to content

Commit

Permalink
ES Modules support
Browse files Browse the repository at this point in the history
  • Loading branch information
Konard authored and wesleytodd committed May 29, 2023
1 parent c1d625c commit cf42372
Showing 1 changed file with 19 additions and 11 deletions.
30 changes: 19 additions & 11 deletions lib/load-migrations.js
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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) {
Expand All @@ -70,6 +76,8 @@ function loadMigrationsIntoSet (options, fn) {

// Successfully loaded
fn()
})
} catch (e) {
fn(e)
}
})
}

0 comments on commit cf42372

Please sign in to comment.