@nativescript/firebase-database
Version:
NativeScript Firebase - Database
594 lines • 18.3 kB
JavaScript
import { deserialize, firebase, FirebaseApp, FirebaseError } from '@nativescript/firebase-core';
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,
});
function numberHasDecimals(item) {
return !(item % 1 === 0);
}
function numberIs64Bit(item) {
return item < -Math.pow(2, 31) + 1 || item > Math.pow(2, 31) - 1;
}
export function serialize(data) {
switch (typeof data) {
case 'string':
case 'boolean': {
return data;
}
case 'number': {
const hasDecimals = numberHasDecimals(data);
if (hasDecimals) {
return NSNumber.numberWithDouble(data);
}
else {
return NSNumber.numberWithLongLong(data);
}
}
case 'object': {
if (data instanceof Date) {
return data.toString();
}
if (!data) {
return NSNull.new();
}
if (Array.isArray(data)) {
return NSArray.arrayWithArray(data.map(serialize));
}
const node = {};
Object.keys(data).forEach((key) => {
const value = data[key];
node[key] = serialize(value);
});
return NSDictionary.dictionaryWithDictionary(node);
}
default:
return NSNull.new();
}
}
function serializeItems(data) {
if (data instanceof ServerValue) {
return data.native;
}
return serialize(data);
}
export class OnDisconnect {
static fromNative(disconnect) {
if (disconnect instanceof FIRDatabaseReference) {
const d = new OnDisconnect();
d._native = disconnect;
return d;
}
return null;
}
get native() {
return this._native;
}
get ios() {
return this.native;
}
cancel(onComplete) {
return new Promise((resolve, reject) => {
if (!this.native) {
reject();
}
else {
this.native.cancelDisconnectOperationsWithCompletionBlock((error, ref) => {
if (error) {
const err = FirebaseError.fromNative(error);
onComplete?.(err);
reject(err);
}
else {
onComplete?.(null);
resolve();
}
});
}
});
}
remove(onComplete) {
return new Promise((resolve, reject) => {
this.native.onDisconnectRemoveValueWithCompletionBlock((error, ref) => {
if (error) {
const err = FirebaseError.fromNative(error);
onComplete?.(err);
reject(err);
}
else {
onComplete?.(null);
resolve();
}
});
});
}
set(value, onComplete) {
return new Promise((resolve, reject) => {
this.native.onDisconnectSetValueWithCompletionBlock(serializeItems(value), (error, ref) => {
if (error) {
const err = FirebaseError.fromNative(error);
onComplete?.(err);
reject(err);
}
else {
onComplete?.(null);
resolve();
}
});
});
}
setWithPriority(value, priority, onComplete) {
return new Promise((resolve, reject) => {
this.native.onDisconnectSetValueAndPriorityWithCompletionBlock(serializeItems(value), priority, (error, ref) => {
if (error) {
const err = FirebaseError.fromNative(error);
onComplete?.(err);
reject(err);
}
else {
onComplete?.(null);
resolve();
}
});
});
}
update(values, onComplete) {
return new Promise((resolve, reject) => {
this.native.onDisconnectUpdateChildValuesWithCompletionBlock(serializeItems(values), (error, ref) => {
if (error) {
const err = FirebaseError.fromNative(error);
onComplete?.(err);
reject(err);
}
else {
onComplete?.(null);
resolve();
}
});
});
}
}
function toFIRDataEventType(event) {
switch (event) {
case 'child_added':
return 0 /* FIRDataEventType.ChildAdded */;
case 'child_changed':
return 2 /* FIRDataEventType.ChildChanged */;
case 'child_moved':
return 3 /* FIRDataEventType.ChildMoved */;
case 'child_removed':
return 1 /* FIRDataEventType.ChildRemoved */;
case 'value':
return 4 /* FIRDataEventType.Value */;
}
}
export class Query {
constructor() {
this._handles = new Map();
}
static fromNative(query) {
if (query instanceof FIRDatabaseQuery) {
const q = new Query();
q._native = query;
return q;
}
return null;
}
get native() {
return this._native;
}
get ios() {
return this.native;
}
get ref() {
return Reference.fromNative(this.native.ref);
}
endAt(value, key) {
if (key) {
return Query.fromNative(this.native.queryEndingAtValueChildKey(value, key));
}
else {
return Query.fromNative(this.native.queryEndingAtValue(value));
}
}
equalTo(value, key) {
if (key) {
return Query.fromNative(this.native.queryEqualToValueChildKey(value, key));
}
else {
return Query.fromNative(this.native.queryEqualToValue(value));
}
}
keepSynced(bool) {
this.native?.keepSynced?.(bool);
}
limitToFirst(limit) {
return Query.fromNative(this.native.queryLimitedToFirst(limit));
}
limitToLast(limit) {
return Query.fromNative(this.native.queryLimitedToLast(limit));
}
off(eventType, callback, context) {
const handle = callback?.['__fbHandle'];
const event = callback?.['__fbEventType'];
if (typeof handle === 'number' && event === eventType) {
if (this._handles.has(callback)) {
this.native.removeObserverWithHandle(handle);
callback['__fbHandle'] = undefined;
callback['__fbEventType'] = undefined;
callback['__fbContext'] = undefined;
this._handles.delete(callback);
}
}
}
on(eventType, callback, cancelCallbackOrContext, context) {
const handle = this.native?.observeEventTypeAndPreviousSiblingKeyWithBlockWithCancelBlock?.(toFIRDataEventType(eventType), (snapshot, key) => {
callback(DataSnapshot.fromNative(snapshot), key);
}, (error) => {
cancelCallbackOrContext?.({
message: error.localizedDescription,
native: error,
});
});
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) => {
this.native.observeSingleEventOfTypeAndPreviousSiblingKeyWithBlockWithCancelBlock?.(toFIRDataEventType(eventType), (snapshot, key) => {
const ss = DataSnapshot.fromNative(snapshot);
successCallback?.(ss, key);
resolve(ss);
}, (error) => {
failureCallbackContext?.({
message: error.localizedDescription,
native: error,
});
reject({
message: error.localizedDescription,
native: error,
});
});
});
}
orderByChild(path) {
return Query.fromNative(this.native.queryOrderedByChild(path));
}
orderByKey() {
return Query.fromNative(this.native.queryOrderedByKey());
}
orderByPriority() {
return Query.fromNative(this.native.queryOrderedByPriority());
}
orderByValue() {
return Query.fromNative(this.native.queryOrderedByValue());
}
startAt(value, key) {
if (key) {
return Query.fromNative(this.native.queryStartingAtValueChildKey(value, key));
}
else {
return Query.fromNative(this.native.queryStartingAtValue(value));
}
}
}
export class ServerValue {
static timeStamp() {
const value = new ServerValue();
value._native = FIRServerValue.timestamp();
return value;
}
static increment(count) {
const value = new ServerValue();
value._native = FIRServerValue.increment(count);
return value;
}
get native() {
return this._native;
}
get ios() {
return this.native;
}
}
export class Reference extends Query {
static fromNative(ref) {
if (ref instanceof FIRDatabaseReference) {
const reference = new Reference();
reference._native = ref;
return reference;
}
return null;
}
get key() {
return this.native.key;
}
get parent() {
return Reference.fromNative(this.native.parent);
}
get ref() {
return Reference.fromNative(this.native.ref);
}
get root() {
return Reference.fromNative(this.native.root);
}
get native() {
return this._native;
}
get ios() {
return this.native;
}
child(path) {
return Reference.fromNative(this.native.child?.(path));
}
onDisconnect() {
return OnDisconnect.fromNative(this.native);
}
push(value, onComplete) {
const id = this.native.childByAutoId();
const thennablePushRef = Reference.fromNative(id);
const pushRef = Reference.fromNative(id);
let promise;
if (value) {
promise = thennablePushRef.set(serialize(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) => {
this.native.removeValueWithCompletionBlock((error, ref) => {
if (error) {
const err = FirebaseError.fromNative(error);
onComplete?.(err);
reject(err);
}
else {
onComplete?.(null);
resolve();
}
});
});
}
set(value, onComplete) {
return new Promise((resolve, reject) => {
this.native.setValueWithCompletionBlock(serializeItems(value), (error, ref) => {
if (error) {
const err = FirebaseError.fromNative(error);
onComplete?.(err);
reject(err);
}
else {
onComplete?.(null);
resolve();
}
});
});
}
setPriority(priority, onComplete) {
return new Promise((resolve, reject) => {
if (!this.native) {
reject();
}
else {
this.native.setPriorityWithCompletionBlock(priority, (error) => {
if (error) {
const err = FirebaseError.fromNative(error);
onComplete?.(err);
reject(err);
}
else {
onComplete?.(null);
resolve();
}
});
}
});
}
setWithPriority(newVal, newPriority, onComplete) {
return new Promise((resolve, reject) => {
this.native.setValueAndPriorityWithCompletionBlock(serializeItems(newVal), newPriority, (error, ref) => {
if (error) {
const err = FirebaseError.fromNative(error);
onComplete?.(err);
reject(err);
}
else {
onComplete?.(null);
resolve();
}
});
});
}
transaction(transactionUpdate, onComplete, applyLocally) {
return new Promise((resolve, reject) => {
this.native.runTransactionBlockAndCompletionBlockWithLocalEvents((data) => {
const newData = transactionUpdate(deserialize(data.value));
data.value = serializeItems(newData);
return FIRTransactionResult.successWithValue(data);
}, (error, commited, snapshot) => {
if (error) {
const err = FirebaseError.fromNative(error);
onComplete?.(err, commited, null);
reject(err);
}
else {
const ss = DataSnapshot.fromNative(snapshot);
onComplete?.(null, commited, ss);
resolve({
commited,
snapshot: ss,
});
}
}, applyLocally || true);
});
}
update(values, onComplete) {
return new Promise((resolve, reject) => {
this.native.updateChildValuesWithCompletionBlock(serializeItems(values), (error, ref) => {
if (error) {
const err = FirebaseError.fromNative(error);
onComplete?.(err);
reject(err);
}
else {
onComplete?.(null);
resolve();
}
});
});
}
}
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 FIRDataSnapshot) {
const ss = new DataSnapshot();
ss._native = snapshot;
return ss;
}
return null;
}
get native() {
return this._native;
}
get ios() {
return this.native;
}
get key() {
return this.native?.key;
}
get ref() {
return Reference.fromNative(this.native.ref);
}
child(path) {
return DataSnapshot.fromNative(this.native.childSnapshotForPath(path));
}
exists() {
return this.native?.exists();
}
exportVal() {
return {
'.priority': this.native.priority,
'.value': deserialize(this.native.value),
};
}
forEach(action) {
let didStop = false;
const children = this.native.children;
let object = children.nextObject();
while (object) {
didStop = action(DataSnapshot.fromNative(object));
if (didStop || !object) {
break;
}
object = children.nextObject();
}
if (didStop) {
return true;
}
if (!object) {
return false;
}
}
getPriority() {
return this.native.priority;
}
hasChild(path) {
return this.native?.hasChild?.(path);
}
hasChildren() {
return this.native?.hasChildren?.();
}
numChildren() {
return this.native?.childrenCount;
}
val() {
return deserialize(this.native.value);
}
}
export class Database {
constructor(app) {
if (app?.native) {
this._native = FIRDatabase.databaseForApp(app.native);
}
else {
if (defaultDatabase) {
return defaultDatabase;
}
defaultDatabase = this;
this._native = FIRDatabase.database();
}
}
useEmulator(host, port) {
this.native.useEmulatorWithHostPort(host, port);
}
get persistenceCacheSizeBytes() {
return this.native.persistenceCacheSizeBytes;
}
set persistenceCacheSizeBytes(bytes) {
this.native.persistenceCacheSizeBytes = bytes;
}
get persistenceEnabled() {
return this.native.persistenceEnabled;
}
set persistenceEnabled(value) {
this.native.persistenceEnabled = value;
}
refFromURL(url) {
return Reference.fromNative(this.native?.referenceFromURL?.(url));
}
setLoggingEnabled(enabled) {
FIRDatabase.setLoggingEnabled(enabled);
}
ref(path) {
return Reference.fromNative(this.native?.referenceWithPath?.(path || '/'));
}
goOffline() {
this.native.goOffline();
}
goOnline() {
this.native.goOnline();
}
get native() {
return this._native;
}
get ios() {
return this.native;
}
get app() {
if (!this._app) {
// @ts-ignore
this._app = FirebaseApp.fromNative(this.native.app);
}
return this._app;
}
}
//# sourceMappingURL=index.ios.js.map