Last active
March 3, 2019 16:23
-
-
Save DubiousS/6afdd7e6c24b15344dbed83649398bf3 to your computer and use it in GitHub Desktop.
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 firebase from 'firebase/app'; | |
import 'firebase/database'; | |
import { firebaseConfig } from '@/common/config'; | |
import { firebaseKeys } from '@/common/constants'; | |
firebase.initializeApp(firebaseConfig); | |
const database = firebase.database(); | |
const snapshotMapper = snap => { | |
const data = snap.val(); | |
return data ? { ...snap.val(), key: snap.key } : {}; | |
}; | |
const getMethod = endpoint => | |
database | |
.ref(endpoint) | |
.once(firebaseKeys.VALUE) | |
.then(snapshotMapper); | |
const postMethod = (endpoint, data) => | |
database | |
.ref(endpoint) | |
.push(data) | |
.then(({ key }) => database.ref(`${endpoint}/${key}`)) | |
.then(ref => ref.once(firebaseKeys.VALUE)) | |
.then(snapshotMapper); | |
const patchMethod = (endpoint, data) => { | |
const entity = database.ref(endpoint); | |
return entity | |
.once(firebaseKeys.VALUE) | |
.then(snapshotMapper) | |
.then(snap => { | |
delete snap.key; | |
delete data.key; | |
if (snap) { | |
return entity.update({ | |
...snap, | |
...data | |
}); | |
} | |
throw new Error('Record not found.'); | |
}) | |
.then(() => database.ref(endpoint)) | |
.then(ref => ref.once(firebaseKeys.VALUE)) | |
.then(snapshotMapper); | |
}; | |
const subscribeMethod = (endpoint, callback) => { | |
database.ref(endpoint).on(firebaseKeys.ONCHANGE, data => { | |
callback(snapshotMapper(data)); | |
}); | |
}; | |
const unsubscribeMethod = endpoint => database.ref(endpoint).off(); | |
export { firebase }; | |
export default { | |
get: getMethod, | |
post: postMethod, | |
patch: patchMethod, | |
subscribe: subscribeMethod, | |
unsubscribe: unsubscribeMethod | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment