forked from colinskow/pouchdb-seed-design
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
90 lines (73 loc) · 2.08 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
var objmap = require('object-map');
var objkeysmap = require('object-keys-map');
var deepEqual = require('deep-equal');
var extend = typeof Object.assign === 'function' ? Object.assign : require('node-extend');
function addDesign(s) {
return '_design/' + s;
}
function normalizeDoc(doc, id) {
function normalize(doc) {
doc = extend({}, doc);
Object.keys(doc).forEach(function(prop) {
var type = typeof doc[prop];
if(type === 'object') {
doc[prop] = normalize(doc[prop]);
} else if(type === 'function') {
doc[prop] = doc[prop].toString();
}
});
return doc;
}
var output = normalize(doc);
output._id = id || doc._id;
output._rev = doc._rev;
return output;
}
function docEqual(local, remote) {
if(!remote) return false;
return deepEqual(local, remote, {strict: true});
}
var pouchSeed = module.exports = function (db, design, cb) {
if (!db || !design) {
throw new TypeError('`db` and `design` are required');
}
var local = objmap(objkeysmap(design, addDesign), normalizeDoc);
var seedPromise = db.allDocs({ include_docs: true, keys: Object.keys(local) })
.then(function (docs) {
var remote = {};
docs.rows.forEach(function (doc) {
if (doc.doc) {
remote[doc.key] = doc.doc;
}
});
var update = Object.keys(local).filter(function(key) {
if(!remote[key]) return true;
local[key]._rev = remote[key]._rev;
return !docEqual(local[key], remote[key]);
}).map(function(key) {
return local[key];
});
if (update.length > 0) {
return db.bulkDocs({ docs: update });
} else {
return Promise.resolve(false);
}
})
.then(function(result) {
if(typeof cb === 'function') {
cb(null, result);
}
return Promise.resolve(result);
})
.catch(function(err) {
if(typeof cb === 'function') {
cb(err, null);
}
console.log(err);
return Promise.reject(err);
});
return seedPromise;
};
if(typeof window === 'object') {
window.pouchSeed = pouchSeed;
}