-
Notifications
You must be signed in to change notification settings - Fork 7
/
couch.js
74 lines (67 loc) · 1.45 KB
/
couch.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
var http = require('http');
var util = require('util');
var crypto = require('crypto');
var getOpts = {
host : "localhost",
port : 5984,
method : "GET",
};
var putOpts = {
host : "localhost",
port : 5984,
method : "PUT",
headers : {
"content-type" : "application/json",
},
};
function update(obj, dbpath, cb) {
if(obj["_id"] == null) {
obj["_id"] = null;
var hash = crypto.createHash('sha256');
hash.update("" + JSON.stringify(obj));
obj["_id"] = hash.digest('hex');
}
getOpts.path = dbpath + obj["_id"];
http.get(getOpts, function(res) {
var data = "";
res.on('data', function(chunk) {
data = data + chunk;
});
res.on('end', function() {
if(res.statusCode < 300) {
obj["_rev"] = JSON.parse(data)["_rev"];
}
putOpts.path = dbpath + obj["_id"];
var req = http.request(putOpts, cb);
req.end(JSON.stringify(obj));
req.on('error', function(e){
util.puts(e);
});
});
}).on('error', function(e) {
util.puts(e);
});
}
function updateList(list, dbpath, cb) {
if(list[0]) {
update(list.pop(), dbpath, function(res) {
res.on('data', util.puts);
res.on('end', function() {
updateList(list, dbpath, cb);
});
});
} else {
cb();
}
}
function createDB(dbpath, cb) {
putOpts.path = dbpath;
var req = http.request(putOpts, cb);
req.end();
req.on('error', function(e) {
util.puts(e);
});
}
module.exports.update = update;
module.exports.updateList = updateList;
module.exports.createDB = createDB;