Skip to content

Instantly share code, notes, and snippets.

@BlackMix
Created March 30, 2019 23:36
Show Gist options
  • Save BlackMix/609dbaf82d185818800f601c3bc8a553 to your computer and use it in GitHub Desktop.
Save BlackMix/609dbaf82d185818800f601c3bc8a553 to your computer and use it in GitHub Desktop.
import firebase from 'firebase'
/**
* firebase config keys
*/
import { config } from '../config/firebase.js'
const app = firebase.initializeApp(config).database()
export class FireBaseProvider
{
constructor(name)
{
this._name = name
this.db = app
}
async init ()
{
await this.db
}
keys ()
{
return new Promise((resolve, reject) => {
this.db.ref(this._name).once('value', result => {
if (result.val() !== null) resolve(Object.keys(result.val()))
else resolve(Object.keys({}))
})
})
}
all ()
{
return new Promise((resolve, reject) => {
this.db.ref(this._name).once('value', result => {
if (result.val() !== null) resolve(result.val())
else resolve({})
})
})
}
get (key)
{
if (typeof key === 'undefined') throw new TypeError('Key must be provided')
if (typeof key !== 'string') throw new TypeError('Key must be a string')
return new Promise((resolve, reject) => {
this.db.ref(this._name).child(key).once('value', result => {
if (result.val() !== null) resolve(result.val())
else resolve(undefined)
})
})
}
get_child (key, child)
{
if (typeof key === 'undefined') throw new TypeError('Key must be provided')
if (typeof key !== 'string') throw new TypeError('Key must be a string')
return new Promise((resolve, reject) => {
this.db.ref(this._name).child(key).child(child).once('value', result => {
if (result.val() !== null) resolve(result.val())
else resolve(undefined)
})
})
}
async set (key, value)
{
if (typeof key === 'undefined') throw new TypeError('Key must be provided')
if (typeof key !== 'string') throw new TypeError('Key must be a string')
if (typeof value === 'undefined') throw new TypeError('Value must be provided')
await this.db.ref(this._name).child(key).set(value)
}
async set_child (key, child, value)
{
if (typeof key === 'undefined') throw new TypeError('Key must be provided')
if (typeof key !== 'string') throw new TypeError('Key must be a string')
if (typeof value === 'undefined') throw new TypeError('Value must be provided')
await this.db.ref(this._name).child(key).child(child).set(value)
}
async remove (key)
{
if (typeof key === 'undefined') throw new TypeError('Key must be provided')
if (typeof key !== 'string') throw new TypeError('Key must be a string')
await this.db.ref(this._name).child(key).remove()
}
async remove_child (key, child)
{
if (typeof key === 'undefined') throw new TypeError('Key must be provided')
if (typeof key !== 'string') throw new TypeError('Key must be a string')
await this.db.ref(this._name).child(key).child(child).remove()
}
async clear ()
{
await {} // later
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment