Created
July 7, 2021 01:09
-
-
Save Orbis25/1ad8748ae4fe36066d772ca22e44e451 to your computer and use it in GitHub Desktop.
firebase helpers
This file contains hidden or 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
import { BaseModel } from "../../base/models/base.model"; | |
import firebase from "firebase"; | |
/** | |
* format all properties timestamp firebase to DateJs | |
* @author Orbis Alonzo Gutierrez | |
* @param data any | |
* @returns T Object | |
*/ | |
const getFormatedFirebaseData = <T>(data: any) => { | |
//get the keys | |
const keys = Object.keys(data); | |
//get the values | |
const values = Object.values(data); | |
//loop for keys and set data | |
values.forEach((value, index) => { | |
if (value instanceof firebase.firestore.Timestamp) { | |
// format date | |
const time = data[keys[index]] as unknown as firebase.firestore.Timestamp; | |
const timeStamp = new firebase.firestore.Timestamp( | |
time.seconds, | |
time.nanoseconds | |
); | |
data[keys[index]] = timeStamp.toDate(); | |
} | |
}); | |
console.log(data); | |
return data as T; | |
}; | |
/** | |
* Return the entity class array from array firebase data | |
* @param docs Array docs results firebase | |
* @author Orbis Alonzo Gutierrez | |
* @returns | |
*/ | |
export const ToEntityArray = <T extends BaseModel>( | |
docs: firebase.firestore.QuerySnapshot<firebase.firestore.DocumentData> | |
): T[] => { | |
//resulst is a object collection | |
const results: T[] = []; | |
//dosc is a firebase collection | |
docs.forEach((doc) => { | |
let data = doc.data() as T; | |
results.push(getFormatedFirebaseData<T>(data)); | |
}); | |
return results; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment