android/js: cleanup / remove redundant code

This commit is contained in:
Salakar 2017-03-10 18:12:46 +00:00
parent eab45d7dc8
commit 50d176427f
5 changed files with 64 additions and 238 deletions

View File

@ -20,6 +20,7 @@
"class-methods-use-this": 0,
"no-plusplus": 0,
"no-underscore-dangle": 0,
"no-return-assign": 0,
"no-undef": 0,
"no-use-before-define": 0,
"arrow-body-style": 0,

View File

@ -3,34 +3,20 @@ package io.invertase.firebase;
import java.util.Map;
import java.util.HashMap;
import android.util.Log;
import android.support.annotation.Nullable;
import com.facebook.react.bridge.Callback;
// react
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
// play services
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.database.ServerValue;
interface KeySetterFn {
String setKeyOrDefault(String a, String b);
}
@SuppressWarnings("WeakerAccess")
public class RNFirebaseModule extends ReactContextBaseJavaModule implements LifecycleEventListener {
private static final String TAG = "RNFirebase";
private FirebaseApp app;
private ReactApplicationContext reactContext;
public RNFirebaseModule(ReactApplicationContext reactContext) {
super(reactContext);
@ -56,138 +42,17 @@ public class RNFirebaseModule extends ReactContextBaseJavaModule implements Life
return result;
}
@ReactMethod
public void configureWithOptions(final ReadableMap params, @Nullable final Callback onComplete) {
Log.i(TAG, "configureWithOptions");
FirebaseOptions.Builder builder = new FirebaseOptions.Builder();
FirebaseOptions defaultOptions = FirebaseOptions.fromResource(getReactApplicationContext().getBaseContext());
if (defaultOptions == null) {
defaultOptions = new FirebaseOptions.Builder().build();
}
KeySetterFn fn = new KeySetterFn() {
public String setKeyOrDefault(
final String key,
final String defaultValue) {
if (params.hasKey(key)) {
// User-set key
final String val = params.getString(key);
Log.d(TAG, "Setting " + key + " from params to: " + val);
return val;
} else if (defaultValue != null && !defaultValue.equals("")) {
Log.d(TAG, "Setting " + key + " from params to: " + defaultValue);
return defaultValue;
} else {
return null;
}
}
};
String val = fn.setKeyOrDefault("applicationId", defaultOptions.getApplicationId());
if (val != null) builder.setApplicationId(val);
val = fn.setKeyOrDefault("apiKey", defaultOptions.getApiKey());
if (val != null) builder.setApiKey(val);
val = fn.setKeyOrDefault("gcmSenderID", defaultOptions.getGcmSenderId());
if (val != null) builder.setGcmSenderId(val);
val = fn.setKeyOrDefault("storageBucket", defaultOptions.getStorageBucket());
if (val != null) builder.setStorageBucket(val);
val = fn.setKeyOrDefault("databaseURL", defaultOptions.getDatabaseUrl());
if (val != null) builder.setDatabaseUrl(val);
val = fn.setKeyOrDefault("databaseUrl", defaultOptions.getDatabaseUrl());
if (val != null) builder.setDatabaseUrl(val);
val = fn.setKeyOrDefault("clientId", defaultOptions.getApplicationId());
if (val != null) builder.setApplicationId(val);
// if (params.hasKey("applicationId")) {
// final String applicationId = params.getString("applicationId");
// Log.d(TAG, "Setting applicationId from params " + applicationId);
// builder.setApplicationId(applicationId);
// }
// if (params.hasKey("apiKey")) {
// final String apiKey = params.getString("apiKey");
// Log.d(TAG, "Setting API key from params " + apiKey);
// builder.setApiKey(apiKey);
// }
// if (params.hasKey("APIKey")) {
// final String apiKey = params.getString("APIKey");
// Log.d(TAG, "Setting API key from params " + apiKey);
// builder.setApiKey(apiKey);
// }
// if (params.hasKey("gcmSenderID")) {
// final String gcmSenderID = params.getString("gcmSenderID");
// Log.d(TAG, "Setting gcmSenderID from params " + gcmSenderID );
// builder.setGcmSenderId(gcmSenderID);
// }
// if (params.hasKey("storageBucket")) {
// final String storageBucket = params.getString("storageBucket");
// Log.d(TAG, "Setting storageBucket from params " + storageBucket);
// builder.setStorageBucket(storageBucket);
// }
// if (params.hasKey("databaseURL")) {
// final String databaseURL = params.getString("databaseURL");
// Log.d(TAG, "Setting databaseURL from params " + databaseURL);
// builder.setDatabaseUrl(databaseURL);
// }
// if (params.hasKey("clientID")) {
// final String clientID = params.getString("clientID");
// Log.d(TAG, "Setting clientID from params " + clientID);
// builder.setApplicationId(clientID);
// }
try {
Log.i(TAG, "Configuring app");
if (app == null) {
app = FirebaseApp.initializeApp(reactContext, builder.build());
}
Log.i(TAG, "Configured");
WritableMap resp = Arguments.createMap();
resp.putString("msg", "success");
onComplete.invoke(null, resp);
} catch (Exception ex) {
Log.e(TAG, "ERROR configureWithOptions");
Log.e(TAG, ex.getMessage());
WritableMap resp = Arguments.createMap();
resp.putString("msg", ex.getMessage());
onComplete.invoke(resp);
}
}
@ReactMethod
public void serverValue(@Nullable final Callback onComplete) {
WritableMap timestampMap = Arguments.createMap();
for (Map.Entry<String, String> entry : ServerValue.TIMESTAMP.entrySet()) {
timestampMap.putString(entry.getKey(), entry.getValue());
}
WritableMap map = Arguments.createMap();
map.putMap("TIMESTAMP", timestampMap);
if (onComplete != null) onComplete.invoke(null, map);
}
// Internal helpers
@Override
public void onHostResume() {
WritableMap params = Arguments.createMap();
params.putBoolean("isForground", true);
params.putBoolean("isForeground", true);
Utils.sendEvent(getReactApplicationContext(), "RNFirebaseAppState", params);
}
@Override
public void onHostPause() {
WritableMap params = Arguments.createMap();
params.putBoolean("isForground", false);
params.putBoolean("isForeground", false);
Utils.sendEvent(getReactApplicationContext(), "RNFirebaseAppState", params);
}
@ -200,9 +65,6 @@ public class RNFirebaseModule extends ReactContextBaseJavaModule implements Life
public Map<String, Object> getConstants() {
final Map<String, Object> constants = new HashMap<>();
constants.put("googleApiAvailability", getPlayServicesStatus());
// TODO remove once this has been moved on ios
constants.put("serverValueTimestamp", ServerValue.TIMESTAMP);
return constants;
}
}

View File

@ -5,8 +5,7 @@
import { NativeModules, NativeEventEmitter } from 'react-native';
import Log from './utils/log';
import { promisify } from './utils';
import Singleton from './utils/singleton';
import { isObject } from './utils';
// modules
import Auth from './modules/auth';
@ -16,7 +15,6 @@ import Messaging from './modules/messaging';
import Analytics from './modules/analytics';
import Crash from './modules/crash';
let log;
const instances = { default: null };
const FirebaseModule = NativeModules.RNFirebase;
const FirebaseModuleEvt = new NativeEventEmitter(FirebaseModule);
@ -24,36 +22,25 @@ const FirebaseModuleEvt = new NativeEventEmitter(FirebaseModule);
/**
* @class Firebase
*/
export default class Firebase extends Singleton {
export default class Firebase {
/**
*
* @param options
*/
constructor(options: Object = {}) {
const instance = super(options);
this.eventHandlers = {};
this.debug = options.debug || false;
this.options = Object.assign({ errorOnMissingPlayServices: true }, options);
instance.options = Object.assign({ errorOnMissingPlayServices: true }, options);
instance._debug = instance.options.debug || false;
if (this.debug) {
Log.enable(this._debug);
}
Log.enable(instance._debug);
log = instance._log = new Log('firebase');
this._log = new Log('firebase');
log.info('Creating new firebase instance');
instance._remoteConfig = instance.options.remoteConfig || {};
delete instance.options.remoteConfig;
instance.configured = instance.options.configure || false;
instance.eventHandlers = {};
log.info('Calling configure with options', instance.options);
instance.configurePromise = instance.configure(instance.options);
instance._auth = new Auth(instance, instance.options);
if (instance.options.errorOnMissingPlayServices && !this.googleApiAvailability.isAvailable) {
this._auth = new Auth(this, this.options);
if (this.options.errorOnMissingPlayServices && !this.googleApiAvailability.isAvailable) {
throw new Error(`Google Play Services is required to run this application but no valid installation was found (Code ${this.googleApiAvailability.status}).`);
}
}
@ -77,38 +64,23 @@ export default class Firebase extends Singleton {
* @returns {*}
*/
static initializeApp(options: Object = {}, name: string = 'default') {
if (!isObject(options)) {
throw new Error('Firebase.initializeApp(options <- requires a configuration object');
}
if (typeof name !== 'string') {
throw new Error('Firebase.initializeApp(options, name <- requires a string value');
}
if (name !== 'default') {
throw new Error('RNFirebase currently only supports one instance of firebase - the default one.');
}
if (!instances[name]) instances[name] = new Firebase(options);
return instances[name];
}
/**
*
* @param opts
* @returns {Promise.<TResult>|*|Promise.<T>}
*/
configure(opts: Object = {}) {
if (!this.configurePromise) {
const firebaseOptions = Object.assign({}, this.options, opts);
this.configurePromise = promisify('configureWithOptions', FirebaseModule)(firebaseOptions)
.then((configuredProperties) => {
log.info('Native configureWithOptions success', configuredProperties);
this.configured = true;
this.firebaseOptions = configuredProperties;
return configuredProperties;
}).catch((err) => {
log.info('Native error occurred while calling configure', err);
});
}
return this.configurePromise;
}
onReady(cb: Function) {
// TODO wut o.O
return this.configurePromise = this.configurePromise.then(cb);
}
/**
* Wrappers
* We add methods from each wrapper to this instance
@ -119,7 +91,6 @@ export default class Firebase extends Singleton {
return this._auth;
}
database() {
if (!this._db) {
this._db = new Database(this);
@ -127,7 +98,6 @@ export default class Firebase extends Singleton {
return this._db;
}
analytics() {
if (!this._analytics) {
this._analytics = new Analytics(this);
@ -191,16 +161,6 @@ export default class Firebase extends Singleton {
return this._constants;
}
/**
* Set the redux store helper
*/
setStore(store: Object) {
if (store) {
this.log.info('Setting the store for Firebase instance');
this._store = store;
}
}
/**
* Global event handlers for the single Firebase instance
*/

View File

@ -13,7 +13,6 @@ const logs = {};
type FirebaseOptions = {};
// TODO cleanup
export class Base extends EventEmitter {
constructor(firebase: Object, options: FirebaseOptions = {}) {
super();
@ -22,10 +21,13 @@ export class Base extends EventEmitter {
this.options = Object.assign({}, firebase.options, options);
}
// Logger
/**
* Return a namespaced instance of Log
* @returns {*}
*/
get log(): Log {
if (!logs[this.namespace]) logs[this.namespace] = new Log(this.namespace, this.firebase._debug);
return logs[this.namespace];
if (logs[this.namespace]) return logs[this.namespace];
return logs[this.namespace] = new Log(this.namespace, this.firebase._debug);
}
/**
@ -35,35 +37,36 @@ export class Base extends EventEmitter {
return this.firebase.app;
}
whenReady(promise: Promise<*>): Promise<*> {
return this.firebase.configurePromise.then(() => promise);
/**
* Add a native module event subscription
* @param name
* @param handler
* @param nativeModule
* @returns {*}
* @private
*/
_on(name, handler, nativeModule) {
let _nativeModule = nativeModule;
if (!_nativeModule) {
_nativeModule = FirebaseModuleEvt;
}
return this.eventHandlers[name] = _nativeModule.addListener(name, handler);
}
// Event handlers
// proxy to firebase instance
_on(name, cb, nativeModule) {
return new Promise((resolve) => {
// if (!this.eventHandlers[name]) {
// this.eventHandlers[name] = {};
// }
if (!nativeModule) {
nativeModule = FirebaseModuleEvt;
}
const sub = nativeModule.addListener(name, cb);
this.eventHandlers[name] = sub;
resolve(sub);
});
}
/**
* Remove a native module event subscription
* @param name
* @private
*/
_off(name): void {
const subscription = this.eventHandlers[name];
if (!subscription) return;
_off(name) {
return new Promise((resolve) => {
if (this.eventHandlers[name]) {
const subscription = this.eventHandlers[name];
subscription.remove(); // Remove subscription
delete this.eventHandlers[name];
resolve(subscription);
}
});
subscription.remove();
delete this.eventHandlers[name];
}
}

View File

@ -170,12 +170,12 @@ export default class Database extends Base {
*/
_setPersistence(enable: boolean = true) {
if (this.persistenceEnabled !== enable) {
this.log.debug(`${enable ? 'Enabling' : 'Disabling'} persistence`);
this.persistenceEnabled = enable;
return this.whenReady(promisify('enablePersistence', FirebaseDatabase)(enable));
this.log.debug(`${enable ? 'Enabling' : 'Disabling'} persistence.`);
return promisify('enablePersistence', FirebaseDatabase)(enable);
}
return this.whenReady(Promise.resolve({ status: 'Already enabled' }));
return Promise.reject({ status: 'Already enabled' });
}
/**