Skip to content

Instantly share code, notes, and snippets.

@DubiousS
Last active March 3, 2019 16:23
Show Gist options
  • Save DubiousS/6afdd7e6c24b15344dbed83649398bf3 to your computer and use it in GitHub Desktop.
Save DubiousS/6afdd7e6c24b15344dbed83649398bf3 to your computer and use it in GitHub Desktop.
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