UNPKG

2.33 kBJavaScriptView Raw
1'use strict'
2
3var path = require('path')
4var fs = require('fs')
5var Migration = require('./migration')
6
7module.exports = loadMigrationsIntoSet
8
9function loadMigrationsIntoSet (options, fn) {
10 // Process options, set and store are required, rest optional
11 var opts = options || {}
12 if (!opts.set || !opts.store) {
13 throw new TypeError((opts.set ? 'store' : 'set') + ' is required for loading migrations')
14 }
15 var set = opts.set
16 var store = opts.store
17 var migrationsDirectory = path.resolve(opts.migrationsDirectory || 'migrations')
18 var filterFn = opts.filterFunction || (() => true)
19 var sortFn = opts.sortFunction || function (m1, m2) {
20 return m1.title > m2.title ? 1 : (m1.title < m2.title ? -1 : 0)
21 }
22
23 // Load from migrations store first up
24 store.load(function (err, state) {
25 if (err) return fn(err)
26
27 // Set last run date on the set
28 set.lastRun = state.lastRun || null
29
30 // Read migrations directory
31 fs.readdir(migrationsDirectory, function (err, files) {
32 if (err) return fn(err)
33
34 // Filter out non-matching files
35 files = files.filter(filterFn)
36
37 // Create migrations, keep a lookup map for the next step
38 var migMap = {}
39 var migrations = files.map(function (file) {
40 // Try to load the migrations file
41 var mod
42 try {
43 mod = require(path.join(migrationsDirectory, file))
44 } catch (e) {
45 return fn(e)
46 }
47
48 var migration = new Migration(file, mod.up, mod.down, mod.description)
49 migMap[file] = migration
50 return migration
51 })
52
53 // Fill in timestamp from state, or error if missing
54 state.migrations && state.migrations.forEach(function (m) {
55 if (m.timestamp !== null && !migMap[m.title]) {
56 // @TODO is this the best way to handle this?
57 return fn(new Error('Missing migration file: ' + m.title))
58 } else if (!migMap[m.title]) {
59 // Migration existed in state file, but was not run and not loadable
60 return
61 }
62 migMap[m.title].timestamp = m.timestamp
63 })
64
65 // Sort the migrations by their title
66 migrations = migrations.sort(sortFn)
67
68 // Add the migrations to the set
69 migrations.forEach(set.addMigration.bind(set))
70
71 // Successfully loaded
72 fn()
73 })
74 })
75}