Created
June 7, 2017 18:45
-
-
Save jerolan/4523c701f2cd8907b8b9addea8a61a56 to your computer and use it in GitHub Desktop.
My firebase elemental operations
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 * as firebase from 'firebase' | |
if (!firebase.apps.length) { | |
firebase.initializeApp({ | |
apiKey: 'your_api_key', | |
authDomain: 'your_auth_domain', | |
databaseURL: 'your_database_url', | |
projectId: 'your_project_ir', | |
storageBucket: 'your_storage_bucket', | |
messagingSenderId: 'your_messaging_sender_id' | |
}) | |
} | |
global.firebase = firebase | |
export const uploadImage = async ({key, ref, image}) => { | |
try { | |
const storage = firebase.storage() | |
const uploadTask = storage | |
.ref(ref) | |
.putString(image, 'data_url') | |
const imageResult = await new Promise((resolve, reject) => { | |
uploadTask.on( | |
'state_changed', | |
snapshot => true, | |
reject, | |
() => resolve(uploadTask.snapshot.downloadURL) | |
) | |
}) | |
return imageResult | |
} catch (e) { | |
throw e | |
} | |
} | |
export const generateDbKey = ref => { | |
const database = firebase.database() | |
return database.ref(ref).push().key | |
} | |
export const updateDataByKey = async ({key, ref, data}) => { | |
try { | |
const database = firebase.database() | |
const updatedData = await database.ref(ref).update(data) | |
return updatedData | |
} catch (e) { | |
throw e | |
} | |
} | |
export const fetchDataByRef = (ref, cb) => { | |
const database = firebase.database() | |
const dataRef = database.ref(ref) | |
dataRef.on('value', snapshot => { | |
const payload = snapshot.val() | |
if (payload !== null) cb(payload) | |
}) | |
} | |
export const findByKey = async ref => { | |
try { | |
const database = firebase.database() | |
const dataRef = database.ref(ref) | |
const response = await dataRef.once('value') | |
const itExist = response.val() | |
if (itExist) return itExist | |
else throw new Error('Data not exist') | |
} catch (e) { | |
throw e | |
} | |
} | |
export default firebase |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment