-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
82 lines (65 loc) · 1.85 KB
/
index.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
73
74
75
76
77
78
79
80
81
82
'use strict';
var stream = require('stream');
var replicationStream = require('pouchdb-replication-stream');
var concat = require('concat-stream');
var Promise = require('promise');
var PouchDB = require('pouchdb');
var util = require('util');
var ReplicatorCommon = require('replicate-common');
var PouchReplicator = function(name, pouchDb, replicationOptions) {
ReplicatorCommon.call(this, name);
// PouchReplicator
this.pouchDb = pouchDb;
this.replicationOptions = replicationOptions;
this.marker = '__end__';
this.replData = [];
PouchDB.plugin(replicationStream.plugin);
PouchDB.adapter('writableStream', replicationStream.adapters.writableStream);
};
util.inherits(PouchReplicator, ReplicatorCommon);
module.exports = PouchReplicator;
PouchReplicator.prototype._createStream = function(data) {
var s = new stream.Readable();
s._read = function() {};
s.push(data);
s.push(null);
return s;
};
PouchReplicator.prototype._getAndClearData = function() {
var self = this;
var data = self.replData.join('');
self.replData = [];
var s = self._createStream(data);
self.pouchDb.load(s, this.replicationOptions)
.then(function(res) {
self.emit('endpeerreplicate');
});
};
PouchReplicator.prototype.receiveData = function(chunk) {
var self = this;
// note double-equals to coerce arraybuffer to string
if (chunk == self.marker) {
self._getAndClearData();
} else {
self.replData.push(chunk);
}
};
/**
* Start PouchDB replication
@ @return {Promise}
*/
PouchReplicator.prototype.replicate = function() {
var self = this;
var database = '';
var concatStream = concat({encoding: 'string'}, function (line) {
database += line;
});
var p = self.pouchDb.dump(concatStream)
.then(function() {
self.streams.forEach(function(s) {
s.write(database);
s.write(self.marker);
});
});
return p;
};