This repository has been archived by the owner on Jun 17, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 47
/
angular-pouchdb.js
118 lines (109 loc) · 3.05 KB
/
angular-pouchdb.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
113
114
115
116
117
118
'use strict';
angular.module('pouchdb', [])
.constant('POUCHDB_METHODS', {
destroy: 'qify',
put: 'qify',
post: 'qify',
get: 'qify',
remove: 'qify',
bulkDocs: 'qify',
bulkGet: 'qify',
allDocs: 'qify',
putAttachment: 'qify',
getAttachment: 'qify',
removeAttachment: 'qify',
query: 'qify',
viewCleanup: 'qify',
info: 'qify',
compact: 'qify',
revsDiff: 'qify',
changes: 'eventEmitter',
sync: 'eventEmitter',
replicate: 'replicate'
})
.service('pouchDBDecorators', function($q) {
var self = this;
this.qify = function(fn) {
return function() {
return $q.when(fn.apply(this, arguments));
};
};
this.eventEmitter = function(fn) {
return function() {
var deferred = $q.defer();
var emitter = fn.apply(this, arguments)
.on('change', function(change) {
return deferred.notify({
change: change
});
})
.on('paused', function(paused) {
return deferred.notify({
paused: paused
});
})
.on('active', function(active) {
return deferred.notify({
active: active
});
})
.on('denied', function(denied) {
return deferred.notify({
denied: denied
});
})
.on('complete', function(response) {
return deferred.resolve(response);
})
.on('error', function(error) {
return deferred.reject(error);
});
emitter.$promise = deferred.promise;
return emitter;
};
};
this.replicate = function(fn, db) {
var getter = Object.keys(fn).reduce(function(index, key) {
index[key] = self.eventEmitter(db.replicate[key]);
return index;
}, {});
Object.defineProperty(db, 'replicate', {
get: function() {
return getter;
}
});
};
})
.provider('pouchDB', function(POUCHDB_METHODS) {
var self = this;
self.methods = POUCHDB_METHODS;
self.$get = function($window, pouchDBDecorators) {
function wrapMethods(db, methods, parent) {
for (var method in methods) {
var wrapFunction = methods[method];
var wrappedFunction;
if (!angular.isString(wrapFunction)) {
wrapMethods(db, wrapFunction, method);
continue;
}
wrapFunction = pouchDBDecorators[wrapFunction];
if (!parent) {
wrappedFunction = wrapFunction(db[method], db);
if (wrappedFunction) {
db[method] = wrappedFunction;
}
continue;
}
wrappedFunction = wrapFunction(db[parent][method]);
if (wrappedFunction) {
db[parent][method] = wrappedFunction;
}
}
return db;
}
return function pouchDB(name, options) {
var db = new $window.PouchDB(name, options);
return wrapMethods(db, self.methods);
};
};
});