1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 | 'use strict';
|
15 |
|
16 | const async = require('async');
|
17 | const error = require('./error.js');
|
18 | const events = require('events');
|
19 |
|
20 | module.exports = function(db, options) {
|
21 | const ee = new events.EventEmitter();
|
22 | const start = new Date().getTime();
|
23 | let batch = 0;
|
24 | let hasErrored = false;
|
25 | let startKey = null;
|
26 | let total = 0;
|
27 |
|
28 | async.doUntil(
|
29 | function(callback) {
|
30 |
|
31 |
|
32 | const opts = { db: db.db, limit: options.bufferSize, includeDocs: true };
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 | if (startKey) opts.startkey = `${startKey}\0`;
|
39 | db.service.postAllDocs(opts).then(response => {
|
40 | const body = response.result;
|
41 | if (!body.rows) {
|
42 | ee.emit('error', new error.BackupError(
|
43 | 'AllDocsError', 'ERROR: Invalid all docs response'));
|
44 | callback();
|
45 | } else {
|
46 | if (body.rows.length < opts.limit) {
|
47 | startKey = null;
|
48 | } else {
|
49 | startKey = body.rows[opts.limit - 1].id;
|
50 | }
|
51 |
|
52 | const docs = [];
|
53 | body.rows.forEach(function(doc) {
|
54 | docs.push(doc.doc);
|
55 | });
|
56 |
|
57 | if (docs.length > 0) {
|
58 | ee.emit('received', {
|
59 | batch: batch++,
|
60 | data: docs,
|
61 | length: docs.length,
|
62 | time: (new Date().getTime() - start) / 1000,
|
63 | total: total += docs.length
|
64 | });
|
65 | }
|
66 | callback();
|
67 | }
|
68 | }).catch(err => {
|
69 | err = error.convertResponseError(err);
|
70 | ee.emit('error', err);
|
71 | hasErrored = true;
|
72 | callback();
|
73 | });
|
74 | },
|
75 | function(callback) { callback(null, hasErrored || startKey == null); },
|
76 | function() { ee.emit('finished', { total: total }); }
|
77 | );
|
78 |
|
79 | return ee;
|
80 | };
|