forked from deltaepsilon/firebase-paginator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bizboard-firebase-paginator.js
289 lines (254 loc) · 9.46 KB
/
bizboard-firebase-paginator.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
var isBrowser = typeof global != 'object' || typeof global.process != 'object';
function FirebasePaginator(ref, defaults) {
var paginator = this;
var defaults = defaults || {};
var pageSize = defaults.pageSize ? parseInt(defaults.pageSize, 10) : 10;
var isFinite = defaults.finite ? defaults.finite : false;
var auth = defaults.auth;
this.ref = ref;
// Events
this.listen = function(callback) {
paginator.allEventHandler = callback;
};
var events = {};
var fire = function(eventName, payload) {
if (typeof paginator.allEventHandler === 'function') {
paginator.allEventHandler.call(paginator, eventName, payload);
}
if (events[eventName] && events[eventName].queue) {
var queue = events[eventName].queue.reverse();
var i = queue.length;
while (i--) {
if (typeof queue[i] === 'function') {
queue[i].call(paginator, payload);
}
}
}
};
this.on = function(eventName, callback) {
if (!events[eventName]) {
events[eventName] = {
queue: []
};
}
events[eventName].queue.push(callback);
};
this.hasNext = function() {
return !this.isLastPage;
};
this.off = function(eventName, callback) {
if (events[eventName] && events[eventName].queue) {
var queue = events[eventName].queue;
var i = queue.length;
while (i--) {
if (queue[i] === callback) {
queue.splice(i, 1);
}
}
}
};
this.once = function(eventName, callback) {
return new Promise(function(resolve, reject) {
var handler = function(payload) {
paginator.off(eventName, handler);
if (typeof callback === 'function') {
try {
resolve(callback.call(paginator, payload));
} catch (e) {
reject(e);
}
} else {
resolve(payload);
}
};
paginator.on(eventName, handler);
});
};
/*
* Pagination can be finite or infinite. Infinite pagination is the default.
*/
if (!isFinite) {
// infinite pagination
var setPage = function(cursor, isForward) {
this.ref = ref.orderByKey();
// If there it's forward pagination, use limitToFirst(pageSize + 1) and startAt(theLastKey)
if (isForward) {
// forward pagination
this.ref = this.ref.limitToFirst(pageSize + 1);
if (cursor) {
// check for forward cursor
this.ref = this.ref.startAt(cursor);
}
} else {
// previous pagination
this.ref = this.ref.limitToLast(pageSize + 1);
if (cursor) {
// check for previous cursor
this.ref = this.ref.endAt(cursor);
}
}
return this.ref.once('value').then(
function(snap) {
var keys = [];
var collection = {};
var lastKey;
snap.forEach(function(childSnap) {
keys.push(childSnap.key);
lastKey = childSnap.key;
collection[childSnap.key] = childSnap.val();
});
if (keys.length === pageSize + 1) {
delete collection[keys[keys.length - 1]];
} else {
this.isLastPage = isForward;
}
this.snap = snap;
this.keys = keys;
this.collection = collection;
this.cursor = cursor;
fire('value', snap);
if (this.isLastPage) {
fire('isLastPage');
}
return this;
}.bind(this)
);
}.bind(this);
fire('ready', paginator);
this.isLastPage = false;
this.reset = function() {
return setPage().then(function() {
return fire('reset');
});
};
this.previous = function() {
return setPage(this.cursor).then(
function() {
return fire('previous');
}.bind(this)
);
};
this.next = function() {
var cursor;
if (this.keys && this.keys.length) {
cursor = this.keys[this.keys.length - 1];
}
return setPage(cursor, true).then(function() {
return fire('next');
});
};
} else {
// finite pagination
var queryPath = ref.toString() + '.json?shallow=true';
if (auth) {
queryPath += '&auth=' + auth;
}
var getKeys = function() {
if (isBrowser) {
return new Promise(function(resolve, reject) {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4) {
var response = JSON.parse(request.responseText);
if (request.status === 200) {
resolve(Object.keys(response || {}));
} else {
reject(response);
}
}
};
request.open('GET', queryPath, true);
request.send();
});
} else {
var axios = require('axios');
return axios.get(queryPath).then(function(res) {
return Object.keys(res.data || {});
});
}
};
this.goToPage = function goToPage(pageNumber) {
pageNumber = Math.min(this.pageCount, Math.max(1, parseInt(pageNumber)));
if (Object.keys(this.pages || {}).length) {
// Null check for empty collections
paginator.page = this.pages[pageNumber];
paginator.pageNumber = pageNumber;
paginator.isLastPage = pageNumber === Object.keys(paginator.pages).length;
paginator.ref = ref.orderByKey().limitToLast(pageSize).endAt(paginator.page.endKey);
} else {
paginator.ref = ref.orderByKey().limitToLast(pageSize);
}
return this.ref.once('value').then(function(snap) {
var collection = snap.val();
var keys = [];
snap.forEach(function(childSnap) {
keys.push(childSnap.key);
});
paginator.snap = snap;
paginator.keys = keys;
paginator.collection = collection || {};
fire('value', snap);
if (paginator.isLastPage) {
fire('isLastPage');
}
return paginator;
});
};
this.reset = function() {
return getKeys()
.then(function(keys) {
var orderedKeys = keys.sort();
var keysLength = orderedKeys.length;
var cursors = [];
for (var i = keysLength; i > 0; i -= pageSize) {
cursors.push({
fromStart: {
startRecord: i - pageSize + 1,
endRecord: i
},
fromEnd: {
startRecord: keysLength - i + 1,
endRecord: keysLength - i + pageSize
},
endKey: keys[i - 1]
});
}
var cursorsLength = cursors.length;
var k = cursorsLength;
var pages = {};
while (k--) {
cursors[k].pageNumber = k + 1;
pages[k + 1] = cursors[k];
}
paginator.pageCount = cursorsLength;
paginator.pages = pages;
return pages;
})
.catch(function(err) {
console.log('finite reset pagination error', err);
});
};
this.reset() // Refresh keys and go to first page.
.then(function() {
return paginator.goToPage(1);
})
.then(function() {
fire('ready', paginator);
});
this.previous = function() {
return this.goToPage(Math.min(this.pageCount, this.pageNumber + 1)).then(function() {
return fire('previous');
});
}.bind(paginator);
this.next = function() {
return this.goToPage(Math.max(1, this.pageNumber - 1)).then(function() {
return fire('next');
});
}.bind(paginator);
}
}
if (isBrowser) {
window.FirebasePaginator = FirebasePaginator;
} else {
module.exports = FirebasePaginator;
}