forked from pouchdb/mapreduce
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
57 lines (51 loc) · 1.27 KB
/
utils.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
'use strict';
// uniquify a list, similar to underscore's _.uniq
exports.uniq = function (arr) {
var map = {};
arr.forEach(function (element) {
map[element] = true;
});
return Object.keys(map);
};
// shallow clone an object
exports.clone = function (obj) {
if (typeof obj !== 'object') {
return obj;
}
var result = {};
Object.keys(obj).forEach(function (key) {
result[key] = obj[key];
});
return result;
};
exports.inherits = require('inherits');
// this is essentially the "update sugar" function from daleharvey/pouchdb#1388
exports.retryUntilWritten = function (db, docId, diffFun, cb) {
if (docId && typeof docId === 'object') {
docId = docId._id;
}
if (typeof docId !== 'string') {
return cb(new Error('doc id is required'));
}
db.get(docId, function (err, doc) {
if (err) {
if (err.name !== 'not_found') {
return cb(err);
}
return tryAndPut(db, diffFun({_id : docId}), diffFun, cb);
}
doc = diffFun(doc);
tryAndPut(db, doc, diffFun, cb);
});
};
function tryAndPut(db, doc, diffFun, cb) {
db.put(doc, function (err) {
if (err) {
if (err.name !== 'conflict') {
return cb(err);
}
return exports.retryUntilWritten(db, doc, diffFun, cb);
}
cb(null);
});
}