forked from mmalecki/couchdb-seed-design
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
112 lines (90 loc) · 2.32 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
var objmap = require('object-map');
var objfilter = require('object-filter');
var objkeysmap = require('object-keys-map');
var objmaptoarr = require('object-map-to-array');
var objsome = require('object-some');
function addDesign(s) {
return '_design/' + s;
}
function normalizeDoc(doc, id) {
var result = {
_id: id || doc._id,
_rev: doc._rev,
views: (doc.views && objmap(doc.views, normalizeView)) || {},
updates: (doc.updates && objmap(doc.updates, normalizeUpdate)) || {}
};
if (doc.validate_doc_update) {
result.validate_doc_update = doc.validate_doc_update;
}
return result;
}
function normalizeUpdate(update) {
return update.toString();
}
function updatesEqual(a, b) {
return !objsome(a, function (v, k) {
return v !== b[k];
});
}
function normalizeView(view) {
var r = {};
if (typeof view === 'function' || typeof view === 'string') {
return { map: view.toString() };
}
// Make sure that functions are stringified.
if (view.map) {
r.map = view.map.toString();
}
if (view.reduce) {
r.reduce = view.reduce.toString();
}
return r;
}
function viewEqual(a, b) {
return b && a.map === b.map && a.reduce === b.reduce;
}
function viewsEqual(a, b) {
return !objsome(a, function (v, k) {
return !viewEqual(v, b[k]);
});
}
function docEqual(local, remote) {
if (!remote) {
return false;
}
return viewsEqual(local.views, remote.views) &&
updatesEqual(local.updates, remote.updates);
}
module.exports = function (db, design, cb) {
if (!db || !design) {
throw new TypeError('`db` and `design` are required');
}
var local = objmap(objkeysmap(design, addDesign), normalizeDoc);
db.fetch({ keys: Object.keys(local) }, function (err, docs) {
var diff;
var remote = {};
var update;
if (err) {
return cb && cb(err);
}
docs.rows.forEach(function (doc) {
if (doc.doc) {
remote[doc.key] = normalizeDoc(doc.doc);
}
});
update = objmaptoarr(objfilter(local, function (value, key) {
return !docEqual(value, remote[key]);
}), function (v, k) {
if (remote[k]) {
v._rev = remote[k]._rev;
}
return v;
});
if (update.length === 0) {
return cb && cb(null, false);
}
db.bulk({ docs: update }, function (err) {
cb && cb(err, true);
});
});
};