Created
August 2, 2017 20:16
-
-
Save kurapatijayaram/32f4dc8e49948b07a9caba1a6b4449c7 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
//Typescript version | |
class Pagination { | |
public dataRef: string; | |
public perPage: number; | |
public order: string; | |
public hasRecords: boolean = true; | |
private _pageRecordCount: number = 0; | |
private _cursor: string = ""; | |
constructor(dataRef: string, perPage?: number, order?: string){ | |
this.dataRef = dataRef; | |
this.perPage = perPage || 10; | |
this.order = order || 'dsc'; | |
} | |
private _handleData(data: any){ | |
let currentRecords = []; | |
this.hasRecords = false; | |
this._pageRecordCount = 0; | |
this._cursor = ""; | |
if(data){ | |
let entities = data; | |
let entityKeys = Object.keys(entities); | |
if(entityKeys.length > this.perPage){ | |
(this.order == 'asc') ? (this._cursor = entityKeys.pop()) : (this._cursor = entityKeys.shift()); | |
this.hasRecords = true; | |
} | |
for(let entity of entityKeys){ | |
this._pageRecordCount++; | |
if(this._pageRecordCount <= this.perPage){ | |
let tempData = entities[entity]; | |
tempData["id"] = entity; | |
(this.order == 'asc') ? (currentRecords.push(tempData)) : (currentRecords.unshift(tempData)); | |
} | |
} | |
} | |
return new Promise((resolve, reject) => { | |
resolve(currentRecords); | |
}); | |
} | |
public fetchRecords(){ | |
let databaseRef = firebase.database().ref(this.dataRef); | |
let orderByRef = databaseRef.orderByKey(); | |
let filterRef; | |
let 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((data) => { | |
return this._handleData(data.val()); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment