-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
92 lines (87 loc) · 2.44 KB
/
Copy pathindex.js
File metadata and controls
92 lines (87 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/* eslint no-await-in-loop:0 */
/**
* @module migration
*/
async function waitForMigrationFinish(store, collection, interval) {
const migDoc = await store.findOne(collection);
if (!migDoc) {
return {};
}
if (migDoc.isMigrating) {
await AppImport('.util').delay(interval);
await waitForMigrationFinish(store, collection, interval);
return false;
}
return migDoc;
}
/**
* The Migration class
* @class
*/
class Migration {
/**
* Create an instance of migration class
* @param {object} configOptions - the global config
*/
constructor(configOptions) {
this.migdir = AppImport('.util').resolvePath(configOptions.migrationdir, 'migrations');
this.store = configOptions.$store;
this.logger = configOptions.$logger;
this.collection = AppImport('.util')
.lastValue(configOptions, 'migration', 'collection') || 'migration';
this.interval = AppImport('.util')
.lastValue(configOptions, 'migration', 'interval') || 1000;
}
/**
* start the migration
*/
async start() {
this.store.mkcoll('migration');
let migDoc = (await waitForMigrationFinish(this.store, this.collection, this.interval));
if (migDoc && !(migDoc.isMigrating)) {
const retOb = await this.store.write(this.collection, migDoc._id, { isMigrating: true });
if (!migDoc._id) {
migDoc = retOb;
}
let migs;
try {
migs = AppImport('fs').readdirSync(this.migdir);
} catch (er) {
if (er.code === 'ENOENT') {
migs = [];
} else {
throw er;
}
}
const runLen = migs.length;
const undo = [];
let foundErr = false;
for (let run = migDoc.lastMigrationNumber; run < runLen; run += 1) {
const mig = AppImport(migs[run]);
try {
await mig.up(this.store, this.logger);
} catch (er) {
foundErr = er;
break;
}
undo.push(mig.down);
}
let newMigNum = migs.length;
if (foundErr) {
const undoLen = undo.length;
this.logger.error(foundErr);
for (let k = 0; k < undoLen; k += 1) {
if (typeof undo[k] === 'function') {
await undo[k](this.store, this.logger);
}
}
newMigNum = migDoc.lastMigrationNumber;
}
await this.store.write(this.collection, migDoc._id, {
isMigrating: false,
lastMigrationNumber: newMigNum,
});
}
}
}
export default Migration;