UNPKG

2.37 kBJavaScriptView Raw
1'use strict';
2
3const fs = require('fs');
4const MigrationTable = require('./MigrationTable');
5
6class Dynograte {
7 constructor(options) {
8 this.migrationTable = null;
9 this.dynamodb = options.dynamodb;
10 this.migrationTableName = options.migrationTableName;
11
12 let migrationDir = options.migrationDir;
13 this.migrationDir = migrationDir && migrationDir.replace(/\/$/, '');
14 }
15
16 migrate(migrators) {
17 return new Promise((resolve, reject) => {
18 let dynamodb = this.dynamodb;
19
20 MigrationTable.create(dynamodb, this.migrationTableName)
21 .then((migrationTable) => {
22 this.migrationTable = migrationTable;
23
24 let promise = Promise.resolve();
25
26 if (migrators) {
27 if (typeof migrators === 'function') {
28 promise = promise.then(() => migrators(dynamodb));
29 } else {
30 migrators.map(migrator => {
31 promise = promise.then(() => migrator(dynamodb));
32 });
33 }
34 resolve(promise);
35 } else {
36 fs.readdir(this.migrationDir, (err, files) => {
37 if (err) {
38 reject(err);
39 return;
40 }
41
42 files.forEach(fileName => {
43 let file = require(`${this.migrationDir}/${fileName}`);
44 promise = promise.then(() => {
45 let fileId;
46 // Check if this migration file has already been ran according
47 // to the migration table. If it has, we skip it, otherwise
48 // we run it and insert it into the table.
49 return migrationTable.alreadyRan(fileName)
50 .then(exists => {
51 if (!exists && file.up) {
52 return migrationTable.insert(fileName)
53 .then(id => {
54 fileId = id;
55 return file.up(dynamodb);
56 })
57 .then(() => {
58 return migrationTable.updatePending(fileId, false);
59 });
60 }
61 });
62 });
63 });
64
65 resolve(promise);
66 });
67 }
68 })
69 .catch((err) => reject(err));
70 });
71 }
72}
73
74module.exports = Dynograte;