/
up.js
54 lines (45 loc) · 1.76 KB
/
up.js
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
const _ = require("lodash");
const pEachSeries = require("p-each-series");
const { promisify } = require("util");
const fnArgs = require('fn-args');
const status = require("./status");
const config = require("../env/config");
const migrationsDir = require("../env/migrationsDir");
const hasCallback = require('../utils/has-callback');
module.exports = async (db, client) => {
const statusItems = await status(db);
const pendingItems = _.filter(statusItems, { appliedAt: "PENDING" });
const migrated = [];
const migrationBlock = Date.now();
const migrateItem = async item => {
try {
const migration = await migrationsDir.loadMigration(item.fileName);
const up = hasCallback(migration.up) ? promisify(migration.up) : migration.up;
if (hasCallback(migration.up) && fnArgs(migration.up).length < 3) {
// support old callback-based migrations prior to migrate-mongo 7.x.x
await up(db);
} else {
await up(db, client);
}
} catch (err) {
const error = new Error(
`Could not migrate up ${item.fileName}: ${err.message}`
);
error.stack = err.stack;
error.migrated = migrated;
throw error;
}
const { changelogCollectionName, useFileHash } = await config.read();
const changelogCollection = db.collection(changelogCollectionName);
const { fileName, fileHash } = item;
const appliedAt = new Date();
try {
await changelogCollection.insertOne(useFileHash === true ? { fileName, fileHash, appliedAt, migrationBlock } : { fileName, appliedAt, migrationBlock });
} catch (err) {
throw new Error(`Could not update changelog: ${err.message}`);
}
migrated.push(item.fileName);
};
await pEachSeries(pendingItems, migrateItem);
return migrated;
};