-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
56 lines (50 loc) · 1.45 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
exports.resolveConflicts = function(doc, resolveFun) {
var db = this
return db
.get(doc._id, {
open_revs: doc._conflicts
})
.then(function(responses) {
return responses
.filter(function(response) {
return 'ok' in response
})
.map(function(response) {
return response.ok
})
})
.then(function(conflicts) {
return conflicts.concat(doc)
})
.then(function(docs) {
var wDocs = JSON.parse(JSON.stringify(docs))
var promise = wDocs.reduce(function(promise, doc) {
return promise.then(function(winning) {
return winning && resolveFun(doc, winning);
})
}, Promise.resolve(wDocs.pop()))
return promise.then(function(winning) {
if (!winning) throw({
error: 'conflict_resolution_failed',
reason: 'The conflict could not be resolve, resolveFun did not return a doc'
})
return docs.filter(function(doc) {
return doc._rev !== winning._rev || JSON.stringify(doc) !== JSON.stringify(winning)
})
.map(function(doc) {
if (doc._rev === winning._rev) return winning
return {
_id: doc._id,
_rev: doc._rev,
_deleted: true
}
})
})
})
.then(function(docs) {
return db.bulkDocs(docs)
})
}
if (typeof window !== 'undefined' && window.PouchDB) {
window.PouchDB.plugin(module.exports)
}