@nativescript/firebase-database
Version:
NativeScript Firebase - Database
617 lines • 21.4 kB
JavaScript
import { deserialize, firebase, FirebaseApp, FirebaseError, serialize } from '@nativescript/firebase-core';
import lazy from '@nativescript/core/utils/lazy';
let defaultDatabase;
const fb = firebase();
Object.defineProperty(fb, 'database', {
value: (app) => {
if (!app) {
if (!defaultDatabase) {
defaultDatabase = new Database();
}
return defaultDatabase;
}
return new Database(app);
},
writable: false,
});
const NSOnDisconnect = lazy(() => org.nativescript.firebase.database.FirebaseDatabase.OnDisconnect);
const NSDatabaseReference = lazy(() => org.nativescript.firebase.database.FirebaseDatabase.DatabaseReference);
function serializeItems(data, wrapPrimitives = false) {
if (data instanceof ServerValue) {
return data.native;
}
return serialize(data, wrapPrimitives);
}
export class OnDisconnect {
static fromNative(disconnect) {
if (disconnect instanceof com.google.firebase.database.OnDisconnect) {
const d = new OnDisconnect();
d._native = disconnect;
return d;
}
return null;
}
get native() {
return this._native;
}
get android() {
return this.native;
}
cancel(onComplete) {
return new Promise((resolve, reject) => {
NSOnDisconnect().cancel(this.native, new org.nativescript.firebase.database.FirebaseDatabase.Callback({
onError(error) {
const err = FirebaseError.fromNative(error);
onComplete?.(err);
reject(err);
},
onSuccess(value) {
onComplete?.(null);
resolve();
},
}));
});
}
remove(onComplete) {
return new Promise((resolve, reject) => {
NSOnDisconnect().remove(this.native, new org.nativescript.firebase.database.FirebaseDatabase.Callback({
onError(error) {
const err = FirebaseError.fromNative(error);
onComplete?.(err);
reject(err);
},
onSuccess(value) {
onComplete?.(null);
resolve();
},
}));
});
}
set(value, onComplete) {
return new Promise((resolve, reject) => {
NSOnDisconnect().set(this.native, serializeItems(value, true), new org.nativescript.firebase.database.FirebaseDatabase.Callback({
onError(error) {
const err = FirebaseError.fromNative(error);
onComplete?.(err);
reject(err);
},
onSuccess(value) {
onComplete?.(null);
resolve();
},
}));
});
}
setWithPriority(value, priority, onComplete) {
return new Promise((resolve, reject) => {
NSOnDisconnect().setWithPriority(this.native, serializeItems(value, true), priority, new org.nativescript.firebase.database.FirebaseDatabase.Callback({
onError(error) {
const err = FirebaseError.fromNative(error);
onComplete?.(err);
reject(err);
},
onSuccess(value) {
onComplete?.(null);
resolve();
},
}));
});
}
update(values, onComplete) {
return new Promise((resolve, reject) => {
NSOnDisconnect().update(this.native,
// should auto marshall ?
values, new org.nativescript.firebase.database.FirebaseDatabase.Callback({
onError(error) {
const err = FirebaseError.fromNative(error);
onComplete?.(err);
reject(err);
},
onSuccess(value) {
onComplete?.(null);
resolve();
},
}));
});
}
}
export class Query {
constructor() {
this._handles = new Map();
}
static fromNative(query) {
if (query instanceof com.google.firebase.database.Query) {
const q = new Query();
q._native = query;
return q;
}
return null;
}
get native() {
return this._native;
}
get android() {
return this.native;
}
get ref() {
return Reference.fromNative(this.native.getRef());
}
endAt(value, key) {
if (key) {
return Query.fromNative(this.native.endAt(value, key));
}
else {
return Query.fromNative(this.native.endAt(value));
}
}
equalTo(value, key) {
if (key) {
return Query.fromNative(this.native.equalTo(value, key));
}
else {
return Query.fromNative(this.native.equalTo(value));
}
}
keepSynced(bool) {
this.native?.keepSynced?.(bool);
}
limitToFirst(limit) {
return Query.fromNative(this.native.limitToFirst(limit));
}
limitToLast(limit) {
return Query.fromNative(this.native.limitToLast(limit));
}
off(eventType, callback, context) {
const handle = callback?.['__fbHandle'];
const event = callback?.['__fbEventType'];
if (handle && event === eventType) {
if (this._handles.has(callback)) {
this.native.removeEventListener(handle);
callback['__fbHandle'] = undefined;
callback['__fbEventType'] = undefined;
callback['__fbContext'] = undefined;
this._handles.delete(callback);
}
}
}
on(eventType, callback, cancelCallbackOrContext, context) {
let handle;
if (eventType === 'value') {
handle = this.native.addValueEventListener(new com.google.firebase.database.ValueEventListener({
onDataChange(param0) {
callback?.(DataSnapshot.fromNative(param0), null);
},
onCancelled(param0) {
const err = FirebaseError.fromNative(param0);
cancelCallbackOrContext?.(err);
},
}));
}
else {
handle = this.native.addChildEventListener(new com.google.firebase.database.ChildEventListener({
onChildAdded(param0, param1) {
if (eventType === 'child_added') {
callback?.(DataSnapshot.fromNative(param0), param1);
}
},
onChildChanged(param0, param1) {
if (eventType === 'child_changed') {
callback?.(DataSnapshot.fromNative(param0), param1);
}
},
onChildRemoved(param0) {
if (eventType === 'child_removed') {
callback?.(DataSnapshot.fromNative(param0), null);
}
},
onChildMoved(param0, param1) {
if (eventType === 'child_moved') {
callback?.(DataSnapshot.fromNative(param0), param1);
}
},
onCancelled(param0) {
const err = FirebaseError.fromNative(param0);
cancelCallbackOrContext?.(err);
},
}));
}
callback['__fbHandle'] = handle;
callback['__fbEventType'] = eventType;
callback['__fbContext'] = context;
this._handles.set(callback, handle);
return callback;
}
once(eventType, successCallback, failureCallbackContext) {
return new Promise((resolve, reject) => {
if (eventType === 'value') {
this.native.addListenerForSingleValueEvent(new com.google.firebase.database.ValueEventListener({
onDataChange(param0) {
const snapshot = DataSnapshot.fromNative(param0);
successCallback?.(snapshot, null);
resolve(snapshot);
},
onCancelled(param0) {
const err = FirebaseError.fromNative(param0);
failureCallbackContext?.(err);
reject(err);
},
}));
}
else {
const native = this.native;
const callback = this.native.addChildEventListener(new com.google.firebase.database.ChildEventListener({
onChildAdded(param0, param1) {
if (eventType === 'child_added') {
const snapshot = DataSnapshot.fromNative(param0);
successCallback?.(snapshot, param1);
native.removeEventListener(callback);
resolve(DataSnapshot.fromNative(param0));
}
},
onChildChanged(param0, param1) {
if (eventType === 'child_changed') {
const snapshot = DataSnapshot.fromNative(param0);
successCallback?.(snapshot, param1);
native.removeEventListener(callback);
resolve(snapshot);
}
},
onChildRemoved(param0) {
if (eventType === 'child_removed') {
const snapshot = DataSnapshot.fromNative(param0);
successCallback?.(snapshot, null);
native.removeEventListener(callback);
resolve(snapshot);
}
},
onChildMoved(param0, param1) {
if (eventType === 'child_moved') {
const snapshot = DataSnapshot.fromNative(param0);
successCallback?.(snapshot, param1);
native.removeEventListener(callback);
resolve(snapshot);
}
},
onCancelled(param0) {
const err = FirebaseError.fromNative(param0);
failureCallbackContext?.(err);
native.removeEventListener(callback);
reject(err);
},
}));
}
});
}
orderByChild(path) {
return Query.fromNative(this.native.orderByChild(path));
}
orderByKey() {
return Query.fromNative(this.native.orderByKey());
}
orderByPriority() {
return Query.fromNative(this.native.orderByPriority());
}
orderByValue() {
return Query.fromNative(this.native.orderByValue());
}
startAt(value, key) {
if (key) {
return Query.fromNative(this.android.startAt(value, key));
}
else {
return Query.fromNative(this.android.startAt(value));
}
}
}
export class ServerValue {
static timeStamp() {
const value = new ServerValue();
value._native = com.google.firebase.database.ServerValue.TIMESTAMP;
return value;
}
static increment(count) {
const value = new ServerValue();
value._native = com.google.firebase.database.ServerValue.increment(count);
return value;
}
get native() {
return this._native;
}
get android() {
return this.native;
}
}
export class Reference extends Query {
static fromNative(ref) {
if (ref instanceof com.google.firebase.database.DatabaseReference) {
const reference = new Reference();
reference._native = ref;
return reference;
}
return null;
}
get key() {
return this.native.getKey();
}
get parent() {
return Reference.fromNative(this.native?.getParent?.());
}
get ref() {
return Reference.fromNative(this.native?.getRef?.());
}
get root() {
return Reference.fromNative(this.native?.getRoot?.());
}
get native() {
return this._native;
}
get android() {
return this.native;
}
child(path) {
return Reference.fromNative(this.native.child?.(path));
}
onDisconnect() {
return OnDisconnect.fromNative(this.native.onDisconnect());
}
push(value, onComplete) {
const id = this.native.push();
const thennablePushRef = Reference.fromNative(id);
const pushRef = Reference.fromNative(id);
let promise;
if (value) {
promise = thennablePushRef.set(value, onComplete).then(() => pushRef);
}
else {
promise = Promise.resolve(pushRef);
}
// @ts-ignore
thennablePushRef.then = promise.then.bind(promise);
// @ts-ignore
thennablePushRef.catch = promise.then.bind(promise, undefined);
if (typeof onComplete === 'function') {
promise.catch(() => { });
}
return thennablePushRef;
}
remove(onComplete) {
return new Promise((resolve, reject) => {
NSDatabaseReference().remove(this.native, new org.nativescript.firebase.database.FirebaseDatabase.Callback({
onSuccess(param0) {
onComplete?.(null);
resolve();
},
onError(error) {
const err = FirebaseError.fromNative(error);
onComplete?.(err);
reject(err);
},
}));
});
}
set(value, onComplete) {
return new Promise((resolve, reject) => {
NSDatabaseReference().set(this.native, serializeItems(value, true), new org.nativescript.firebase.database.FirebaseDatabase.Callback({
onSuccess(param0) {
onComplete?.(null);
resolve();
},
onError(error) {
const err = FirebaseError.fromNative(error);
onComplete?.(err);
reject(err);
},
}));
});
}
setPriority(priority, onComplete) {
return new Promise((resolve, reject) => {
NSDatabaseReference().setPriority(this.native, priority, new org.nativescript.firebase.database.FirebaseDatabase.Callback({
onSuccess(param0) {
onComplete?.(null);
resolve();
},
onError(error) {
const err = FirebaseError.fromNative(error);
onComplete?.(err);
reject(err);
},
}));
});
}
setWithPriority(newVal, newPriority, onComplete) {
return new Promise((resolve, reject) => {
NSDatabaseReference().setWithPriority(this.native, serializeItems(newVal, true), newPriority, new org.nativescript.firebase.database.FirebaseDatabase.Callback({
onSuccess(param0) {
onComplete?.(null);
resolve();
},
onError(error) {
const err = FirebaseError.fromNative(error);
onComplete?.(err);
reject(err);
},
}));
});
}
transaction(transactionUpdate, onComplete, applyLocally = true) {
return new Promise((resolve, reject) => {
NSDatabaseReference().transaction(this.native, applyLocally, new org.nativescript.firebase.database.FirebaseDatabase.TransactionCallback({
doTransaction(data) {
const newData = transactionUpdate(deserialize(data));
// TODO improve
return serializeItems(newData, true);
},
onComplete(error, commited, snapshot) {
const ss = DataSnapshot.fromNative(snapshot);
if (error) {
const err = FirebaseError.fromNative(error);
onComplete?.(err, commited, ss);
reject(err);
}
else {
onComplete?.(null, commited, ss);
resolve({
commited,
snapshot: ss,
});
}
},
}));
});
}
update(values, onComplete) {
return new Promise((resolve, reject) => {
NSDatabaseReference().update(this.native, serializeItems(values, true), new org.nativescript.firebase.database.FirebaseDatabase.Callback({
onSuccess(param0) {
onComplete?.(null);
resolve();
},
onError(param0) {
const err = FirebaseError.fromNative(param0);
onComplete?.(err);
reject(err);
},
}));
});
}
}
export class ThenableReference extends Reference {
toString() {
throw new Error('Method not implemented.');
}
then(onfulfilled, onrejected) {
throw new Error('Method not implemented.');
}
}
export class DataSnapshot {
static fromNative(snapshot) {
if (snapshot instanceof com.google.firebase.database.DataSnapshot) {
const ss = new DataSnapshot();
ss._native = snapshot;
return ss;
}
return null;
}
get native() {
return this._native;
}
get android() {
return this.native;
}
get key() {
return this.native?.getKey();
}
get ref() {
return Reference.fromNative(this.native.getRef());
}
child(path) {
return DataSnapshot.fromNative(this.native.child(path));
}
exists() {
return this.native?.exists();
}
exportVal() {
return {
'.priority': this.native.getPriority?.(),
'.value': deserialize(this.native.getValue(true)),
};
}
forEach(action) {
const iterator = this.native.getChildren().iterator();
let stopEnumerate = false;
while (!stopEnumerate) {
if (iterator.hasNext()) {
const object = iterator.next();
stopEnumerate = action(DataSnapshot.fromNative(object));
}
else {
stopEnumerate = true;
}
}
return stopEnumerate;
}
getPriority() {
return this.native.getPriority();
}
hasChild(path) {
return this.native?.hasChild?.(path);
}
hasChildren() {
return this.native?.hasChildren?.();
}
numChildren() {
return this.native?.getChildrenCount();
}
val() {
return deserialize(this.native.getValue());
}
}
export class Database {
constructor(app) {
this._persistenceCacheSizeBytes = 10 * 1024 * 1024;
this._persistenceEnabled = false;
if (app?.native) {
this._native = com.google.firebase.database.FirebaseDatabase.getInstance(app.native);
}
else {
if (defaultDatabase) {
return defaultDatabase;
}
defaultDatabase = this;
this._native = com.google.firebase.database.FirebaseDatabase.getInstance();
}
}
useEmulator(host, port) {
this.native.useEmulator(host === 'localhost' || host === '127.0.0.1' ? '10.0.2.2' : host, port);
}
get persistenceCacheSizeBytes() {
return this._persistenceCacheSizeBytes;
}
set persistenceCacheSizeBytes(bytes) {
try {
this.native.setPersistenceCacheSizeBytes(bytes);
this._persistenceCacheSizeBytes = bytes;
}
catch (e) { }
}
get persistenceEnabled() {
return this._persistenceEnabled;
}
set persistenceEnabled(value) {
try {
this.native.setPersistenceEnabled(value);
this._persistenceEnabled = value;
}
catch (e) { }
}
refFromURL(url) {
return Reference.fromNative(this.native.getReferenceFromUrl(url));
}
setLoggingEnabled(enabled) {
this.native?.setLogLevel?.(enabled);
}
ref(path) {
return Reference.fromNative(this.native?.getReference?.(path || '/'));
}
goOffline() {
this.native.goOffline();
}
goOnline() {
this.native.goOnline();
}
get native() {
return this._native;
}
get android() {
return this.native;
}
get app() {
if (!this._app) {
// @ts-ignore
this._app = FirebaseApp.fromNative(this.native.getApp());
}
return this._app;
}
}
//# sourceMappingURL=index.android.js.map