Created
August 2, 2017 20:18
-
-
Save kurapatijayaram/aa135e83388439f7a16a77d1509e9d6f to your computer and use it in GitHub Desktop.
firebase pagination
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Javascript version | |
var Pagination = (function () { | |
function Pagination(dataRef, perPage, order) { | |
this.hasRecords = true; | |
this._pageRecordCount = 0; | |
this._cursor = ""; | |
this.dataRef = dataRef; | |
this.perPage = perPage || 10; | |
this.order = order || 'dsc'; | |
} | |
Pagination.prototype._handleData = function (data) { | |
var currentRecords = []; | |
this.hasRecords = false; | |
this._pageRecordCount = 0; | |
this._cursor = ""; | |
if (data) { | |
var entities = data; | |
var entityKeys = Object.keys(entities); | |
if (entityKeys.length > this.perPage) { | |
(this.order == 'asc') ? (this._cursor = entityKeys.pop()) : (this._cursor = entityKeys.shift()); | |
this.hasRecords = true; | |
} | |
for (var _i = 0, entityKeys_1 = entityKeys; _i < entityKeys_1.length; _i++) { | |
var entity = entityKeys_1[_i]; | |
this._pageRecordCount++; | |
if (this._pageRecordCount <= this.perPage) { | |
var tempData = entities[entity]; | |
tempData["id"] = entity; | |
(this.order == 'asc') ? (currentRecords.push(tempData)) : (currentRecords.unshift(tempData)); | |
} | |
} | |
} | |
return new Promise(function (resolve, reject) { | |
resolve(currentRecords); | |
}); | |
}; | |
Pagination.prototype.fetchRecords = function () { | |
var _this = this; | |
var databaseRef = firebase.database().ref(this.dataRef); | |
var orderByRef = databaseRef.orderByKey(); | |
var filterRef; | |
var cursorRef; | |
if (this._cursor) { | |
cursorRef = (this.order == 'asc') ? orderByRef.startAt(this._cursor) : orderByRef.endAt(this._cursor); | |
} | |
else { | |
cursorRef = orderByRef; | |
} | |
if (this.order == 'asc') { | |
filterRef = cursorRef.limitToFirst(this.perPage + 1); | |
} | |
else { | |
filterRef = cursorRef.limitToLast(this.perPage + 1); | |
} | |
return filterRef.once("value").then(function (data) { | |
return _this._handleData(data.val()); | |
}); | |
}; | |
return Pagination; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment