react-native-firebase/lib/modules/database/index.js

97 lines
2.3 KiB
JavaScript
Raw Normal View History

/**
2017-03-02 11:40:08 +00:00
* @flow
* Database representation wrapper
*/
import { NativeModules } from 'react-native';
2017-03-02 11:40:08 +00:00
import Reference from './reference';
import TransactionHandler from './transaction';
import ModuleBase from '../../utils/ModuleBase';
import { getNativeModule } from '../../utils/native';
2017-03-02 11:40:08 +00:00
import type App from '../core/firebase-app';
const NATIVE_EVENTS = [
'database_transaction_event',
// 'database_server_offset', // TODO
];
export const MODULE_NAME = 'RNFirebaseDatabase';
export const NAMESPACE = 'database';
2017-03-02 11:40:08 +00:00
/**
* @class Database
*/
export default class Database extends ModuleBase {
_offsetRef: Reference;
_serverTimeOffset: number;
_transactionHandler: TransactionHandler;
constructor(app: App, options: Object = {}) {
super(app, {
events: NATIVE_EVENTS,
moduleName: MODULE_NAME,
namespace: NAMESPACE,
});
this._transactionHandler = new TransactionHandler(this);
2017-08-02 09:38:30 +00:00
if (options.persistence) {
getNativeModule(this).setPersistence(options.persistence);
2017-08-02 09:38:30 +00:00
}
2017-03-02 11:40:08 +00:00
2017-10-05 11:45:54 +00:00
// server time listener
// setTimeout used to avoid setPersistence race conditions
2017-10-05 11:53:47 +00:00
// todo move this and persistence to native side, create a db configure() method natively perhaps?
// todo and then native can call setPersistence and then emit offset events
2017-10-05 11:45:54 +00:00
setTimeout(() => {
this._serverTimeOffset = 0;
this._offsetRef = this.ref('.info/serverTimeOffset');
this._offsetRef.on('value', (snapshot) => {
this._serverTimeOffset = snapshot.val() || this._serverTimeOffset;
});
}, 1);
2017-03-02 11:40:08 +00:00
}
2017-08-02 09:38:30 +00:00
/**
*
* @return {number}
*/
getServerTime(): number {
2017-10-05 11:45:54 +00:00
return new Date(Date.now() + this._serverTimeOffset);
2017-08-02 09:38:30 +00:00
}
2017-03-02 11:40:08 +00:00
/**
*
*/
goOnline(): void {
getNativeModule(this).goOnline();
2017-03-02 11:40:08 +00:00
}
/**
*
*/
goOffline(): void {
getNativeModule(this).goOffline();
}
2017-03-02 11:40:08 +00:00
/**
* Returns a new firebase reference instance
* @param path
* @returns {Reference}
2017-03-02 11:40:08 +00:00
*/
ref(path: string): Reference {
return new Reference(this, path);
2017-03-02 11:40:08 +00:00
}
}
export const statics = {
ServerValue: NativeModules.RNFirebaseDatabase ? {
TIMESTAMP: NativeModules.RNFirebaseDatabase.serverValueTimestamp || { '.sv': 'timestamp' },
} : {},
enableLogging(enabled: boolean) {
if (NativeModules[MODULE_NAME]) {
NativeModules[MODULE_NAME].enableLogging(enabled);
}
},
};