-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
65 lines (58 loc) · 1.6 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
var util = require('util'),
request = require('request'),
Writable = require('stream').Writable;
util.inherits(LogStream, Writable);
function LogStream(db, opts) {
this.db = db;
this.opts = opts || {};
this._createdDb = false;
Writable.call(this, { objectMode: true });
}
LogStream.prototype._write = function(chunk, encoding, callback) {
request.post(
{
url: this.db,
auth: this.opts.auth,
json: chunk
},
function(err, resp, body) {
if (err) return callback(err);
if (resp.statusCode >= 400) {
if (
!this._createdDb &&
resp.statusCode === 404 &&
body &&
(body.reason === 'no_db_file' ||
body.reason.includes('Database does not exist'))
) {
// try to create DB
request.put(
{
url: this.db,
auth: this.opts.auth,
json: true
},
function(err, resp, body) {
this._createdDb = true;
if (err) return callback(err);
if (resp.statusCode >= 400) {
return callback(
new Error(
'Could not create db.' +
(body ? ' ' + (body.reason || body.error) : '')
)
);
}
this._write(chunk, encoding, callback);
}.bind(this)
);
} else {
callback(new Error(body ? body.reason : 'could not POST to CouchDB'));
}
} else {
callback(null);
}
}.bind(this)
);
};
module.exports = LogStream;