-
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathmigrations.js
More file actions
64 lines (59 loc) · 1.71 KB
/
migrations.js
File metadata and controls
64 lines (59 loc) · 1.71 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
import _ from 'lodash';
import { Mongo } from 'meteor/mongo';
export const MigrationHistory = new Mongo.Collection('_cacheMigrations');
let migrations = [];
export function addMigration(collection, insertFn, options) {
let opts = _.clone(options);
if (opts.collection) {
//prevent Error: Converting circular structure to JSON
opts.collection = opts.collection._name;
}
opts = JSON.stringify(opts);
migrations.push({
options: opts,
collectionName: collection._name,
collection: collection,
cacheField: options.cacheField,
fn: insertFn,
});
}
export async function migrate(collectionName, cacheField, selector) {
let migration = _.find(migrations, { collectionName, cacheField });
if (!migration) {
throw new Error(
'no migration found for ' + collectionName + ' - ' + cacheField,
);
} else {
let time = new Date();
let n = 0;
await migration.collection
.find(selector || {})
.forEachAsync(async (doc) => {
await migration.fn(null, doc);
n++;
});
console.log(
`migrated ${cacheField} of ${n} docs in ${
collectionName +
(selector ? ' matching ' + JSON.stringify(selector) : '')
}. It took ${new Date() - time}ms`,
);
}
}
export async function autoMigrate() {
for (const migration of migrations) {
if (
!(await MigrationHistory.findOneAsync({
collectionName: migration.collectionName,
options: migration.options,
}))
) {
await migrate(migration.collectionName, migration.cacheField);
await MigrationHistory.insertAsync({
collectionName: migration.collectionName,
options: migration.options,
date: new Date(),
});
}
}
}