forked from votem/mongo-stream
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongo-stream.js
72 lines (59 loc) · 2.52 KB
/
mongo-stream.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
const MongoClient = require('mongodb').MongoClient;
const ElasticManager = require('./elasticManager');
const CollectionManager = require('./CollectionManager');
class MongoStream {
constructor(elasticManager, db, resumeTokenInterval = 60000) {
this.elasticManager = elasticManager;
this.db = db;
this.collectionManagers = {};
// write resume tokens to file on an interval
setInterval(() => {
const collectionManagers = Object.values(this.collectionManagers);
collectionManagers.forEach(manager => {
manager.writeResumeToken();
});
}, resumeTokenInterval);
}
// constructs and returns a new MongoStream
static async init(options) {
const client = await MongoClient.connect(options.url, options.mongoOpts);
const db = client.db(options.db);
await db.createCollection('init'); // workaround for "MongoError: cannot open $changeStream for non-existent database"
await db.dropCollection('init');
const elasticManager = new ElasticManager(options.elasticOpts, options.mappings, options.bulkSize);
const resumeTokenInterval = options.resumeTokenInterval;
const mongoStream = new MongoStream(elasticManager, db, resumeTokenInterval);
const managerOptions = {
dump: options.dumpOnStart,
ignoreResumeTokens: options.ignoreResumeTokensOnStart,
watch: true
};
await mongoStream.addCollectionManager(options.collections, managerOptions);
return mongoStream;
}
// accepts single collection or array
async addCollectionManager(collections, options) {
if (!Array.isArray(collections)) collections = [collections];
await this.removeCollectionManager(collections);
for (const collection of collections) {
const collectionManager = new CollectionManager(this.db, collection, this.elasticManager);
if (options.dump) {
await collectionManager.elasticManager.deleteElasticCollection(collection);
await collectionManager.dumpCollection();
}
if (options.watch) { collectionManager.watch(options.ignoreResumeTokens) }
this.collectionManagers[collection] = collectionManager;
}
}
async removeCollectionManager(collections) {
if (!Array.isArray(collections)) collections = [collections];
for (const collection of collections) {
if (this.collectionManagers[collection]) {
this.collectionManagers[collection].removeChangeStream();
delete this.collectionManagers[collection];
}
}
return Object.keys(this.collectionManagers);
}
}
module.exports = MongoStream;