-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
65 lines (58 loc) · 1.69 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
/**
* Express Pouchdb Replication Stream
*
* An express endpoint for streaming changes from a
* couch database to the client in bulk.
*
* @author Conor Mac Aoidh <[email protected]>
*/
'use strict';
/*jshint camelcase: false */
var pouch = require('pouchdb');
var pouchRepStream = require('pouchdb-replication-stream');
// register pouch-replication-stream as a plugin
pouch.plugin(pouchRepStream.plugin);
pouch.adapter('writableStream', pouchRepStream.adapters.writableStream);
/**
* ExpressPouchReplicationStream
*
* An express endpoint for streaming changes from a
* couch database to the client in bulk.
*
* @param opts
* - url: full url of couch db location
* - replication: options to be passed to couchdb
* - filter
* - query_params
* see:
*
* http://wiki.apache.org/couchdb/Replication#Filtered_Replication
*/
var ExpressPouchReplicationStream = function(opts){
// parse options
var config = {
url: typeof opts === 'string' ? opts : opts.url,
dbReq: !!opts.dbReq,
replicationOpts : opts.replication || {},
error: opts.error || false
};
// return function that fulfills the request
return function(req, res, next){
var url = config.url;
// db is passed in the request
if(config.dbReq){
url += '/' + req.params.db;
}
// stream db to express response
var db = new pouch(url);
return db.dump(res, config.replicationOpts)
.catch(function(err){
// custom error handler
if(typeof config.error === 'function'){
return config.error(err);
}
res.status(500).send(err);
});
};
};
module.exports = ExpressPouchReplicationStream;