Merge branch 'master' of https://github.com/invertase/react-native-firebase
# Conflicts: # .gitignore # tests/.gitignore # tests/ios/Podfile
This commit is contained in:
commit
f8e97d8bed
|
@ -14,13 +14,37 @@ xcuserdata/
|
||||||
# Android
|
# Android
|
||||||
|
|
||||||
# Built application files
|
# Built application files
|
||||||
android/*/build/
|
**/android/**/build/
|
||||||
|
|
||||||
# Crashlytics configuations
|
# Crashlytics configuations
|
||||||
android/com_crashlytics_export_strings.xml
|
android/com_crashlytics_export_strings.xml
|
||||||
|
|
||||||
# Signing files
|
# Signing files
|
||||||
android/.signing/
|
android/.signing/
|
||||||
|
|
||||||
|
# Local configuration file (sdk path, etc)
|
||||||
|
**/android/local.properties
|
||||||
|
|
||||||
|
# Gradle generated files
|
||||||
|
**/android/.gradle/
|
||||||
|
|
||||||
|
# Signing files
|
||||||
|
android/.signing/
|
||||||
|
|
||||||
|
# User-specific configurations
|
||||||
|
android/.idea/gradle.xml
|
||||||
|
android/.idea/libraries/
|
||||||
|
android/.idea/workspace.xml
|
||||||
|
android/.idea/tasks.xml
|
||||||
|
android/.idea/.name
|
||||||
|
android/.idea/compiler.xml
|
||||||
|
android/.idea/copyright/profiles_settings.xml
|
||||||
|
android/.idea/encodings.xml
|
||||||
|
android/.idea/misc.xml
|
||||||
|
android/.idea/modules.xml
|
||||||
|
android/.idea/scopes/scope_settings.xml
|
||||||
|
android/.idea/vcs.xml
|
||||||
|
**/android/**/*.iml
|
||||||
ios/RnFirebase.xcodeproj/xcuserdata
|
ios/RnFirebase.xcodeproj/xcuserdata
|
||||||
|
|
||||||
# OS-specific files
|
# OS-specific files
|
||||||
|
@ -40,12 +64,17 @@ lib/.watchmanconfig
|
||||||
.idea
|
.idea
|
||||||
coverage
|
coverage
|
||||||
yarn.lock
|
yarn.lock
|
||||||
|
|
||||||
tests/build
|
tests/build
|
||||||
tests/android/gradle
|
|
||||||
tests/ios/Podfile.lock
|
tests/ios/Podfile.lock
|
||||||
tests/android/app/build
|
tests/android/app/build
|
||||||
tests/ios/Pods
|
tests/ios/Pods
|
||||||
|
tests/ios/Podfile.lock
|
||||||
tests/firebase
|
tests/firebase
|
||||||
.gradle
|
.gradle
|
||||||
local.properties
|
local.properties
|
||||||
*.iml
|
*.iml
|
||||||
|
|
||||||
|
**/ios/Pods/**
|
||||||
|
**/ios/ReactNativeFirebaseDemo.xcworkspace/
|
||||||
|
|
||||||
|
|
51
README.md
51
README.md
|
@ -1,4 +1,4 @@
|
||||||
# React Native Firebase<img align="left" src="http://i.imgur.com/01XQL0x.png">
|
# React Native Firebase<a href="https://invertase.io/react-native-firebase"><img align="left" src="http://i.imgur.com/01XQL0x.png"></a>
|
||||||
|
|
||||||
[![Chat](https://img.shields.io/badge/chat-on%20discord-7289da.svg)](https://discord.gg/t6bdqMs)
|
[![Chat](https://img.shields.io/badge/chat-on%20discord-7289da.svg)](https://discord.gg/t6bdqMs)
|
||||||
[![Gitter](https://badges.gitter.im/invertase/react-native-firebase.svg)](https://gitter.im/invertase/react-native-firebase?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
|
[![Gitter](https://badges.gitter.im/invertase/react-native-firebase.svg)](https://gitter.im/invertase/react-native-firebase?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
|
||||||
|
@ -6,15 +6,19 @@
|
||||||
[![License](https://img.shields.io/npm/l/react-native-firebase.svg)](/LICENSE)
|
[![License](https://img.shields.io/npm/l/react-native-firebase.svg)](/LICENSE)
|
||||||
|
|
||||||
**RNFirebase** makes using [Firebase](http://firebase.com) with React Native simple.
|
**RNFirebase** makes using [Firebase](http://firebase.com) with React Native simple.
|
||||||
|
|
||||||
|
> [Documentation](https://invertase.io/react-native-firebase)
|
||||||
|
|
||||||
|
|
||||||
<hr>
|
<hr>
|
||||||
|
|
||||||
### Install
|
### Install
|
||||||
```
|
```bash
|
||||||
npm i react-native-firebase --save
|
npm i react-native-firebase --save
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Platform specific setup guides:
|
#### Platform specific setup guides:
|
||||||
[![ios](https://a.fsdn.com/sd/topics/ios_64.png)](docs/installation.ios.md) [![android](https://a.fsdn.com/sd/topics/android_64.png)](docs/installation.android.md)
|
[![ios](https://a.fsdn.com/sd/topics/ios_64.png)](http://invertase.io/react-native-firebase/#/installation-ios) [![android](https://a.fsdn.com/sd/topics/android_64.png)](http://invertase.io/react-native-firebase/#/installation-android)
|
||||||
|
|
||||||
<hr>
|
<hr>
|
||||||
|
|
||||||
|
@ -30,47 +34,6 @@ The native SDKs also allow us to hook into device sdk's which are not possible w
|
||||||
|
|
||||||
<hr>
|
<hr>
|
||||||
|
|
||||||
### Test app
|
|
||||||
|
|
||||||
To help ensure changes and features work across both iOS & Android, we've developed an app specifically to test `react-native-firebase` against the [`firebase` web SDK](https://www.npmjs.com/package/firebase). Please see the [`tests`](tests/README.md) directory for more information.
|
|
||||||
|
|
||||||
<hr>
|
|
||||||
|
|
||||||
### Examples app
|
|
||||||
|
|
||||||
There's currently a work in progress [examples app](https://github.com/invertase/react-native-firebase-examples) which aims to demonstrate various real world use-case scenarios with React Native & Firebase. We welcome any new examples or updates to existing ones.
|
|
||||||
|
|
||||||
<hr>
|
|
||||||
|
|
||||||
### Documentation
|
|
||||||
|
|
||||||
RNFirebase aims to replicate the Firebase Web SDK as closely as possible. Because of this, the documentation focuses around the installation, differences & best practices of this library. Please see the [Firebase Web SDK](https://firebase.google.com/docs/reference/js/) documentation for Firebase functionality.
|
|
||||||
|
|
||||||
> If you find any discrepancies between the two libraries, please raise an issue or PR.
|
|
||||||
|
|
||||||
* [Firebase Setup](docs/firebase-setup.md)
|
|
||||||
* API
|
|
||||||
* [Authentication](docs/api/authentication.md)
|
|
||||||
* [Realtime Database](docs/api/database.md)
|
|
||||||
* [Analytics](docs/api/analytics.md)
|
|
||||||
* [Storage](docs/api/storage.md)
|
|
||||||
* [Messaging](docs/api/cloud-messaging.md)
|
|
||||||
* [Crash](docs/api/crash.md)
|
|
||||||
* [Transactions](docs/api/transactions.md)
|
|
||||||
* [FAQs / Troubleshooting](docs/faqs.md)
|
|
||||||
|
|
||||||
<hr>
|
|
||||||
|
|
||||||
### Contributing
|
|
||||||
|
|
||||||
We welcome any contribution to the repository. Please ensure your changes to the JavaScript code follow the styling guides controlled by ESlint. Changes to native code should be kept clean and follow the standard of existing code.
|
|
||||||
|
|
||||||
Changes to existing code should ensure all relevant tests on the test app pass. Any new features should have new tests created and ensure all existing tests pass.
|
|
||||||
|
|
||||||
**Project board:** https://github.com/invertase/react-native-firebase/projects
|
|
||||||
|
|
||||||
<hr>
|
|
||||||
|
|
||||||
### License
|
### License
|
||||||
|
|
||||||
- MIT
|
- MIT
|
||||||
|
|
|
@ -78,12 +78,13 @@ public class Utils {
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* @param name
|
* @param name
|
||||||
|
* @param refId
|
||||||
|
* @param listenerId
|
||||||
* @param path
|
* @param path
|
||||||
* @param modifiersString
|
|
||||||
* @param dataSnapshot
|
* @param dataSnapshot
|
||||||
* @return
|
* @return
|
||||||
*/
|
*/
|
||||||
public static WritableMap snapshotToMap(String name, String path, String modifiersString, DataSnapshot dataSnapshot) {
|
public static WritableMap snapshotToMap(String name, int refId, Integer listenerId, String path, DataSnapshot dataSnapshot) {
|
||||||
WritableMap snapshot = Arguments.createMap();
|
WritableMap snapshot = Arguments.createMap();
|
||||||
WritableMap eventMap = Arguments.createMap();
|
WritableMap eventMap = Arguments.createMap();
|
||||||
|
|
||||||
|
@ -106,10 +107,13 @@ public class Utils {
|
||||||
snapshot.putArray("childKeys", Utils.getChildKeys(dataSnapshot));
|
snapshot.putArray("childKeys", Utils.getChildKeys(dataSnapshot));
|
||||||
mapPutValue("priority", dataSnapshot.getPriority(), snapshot);
|
mapPutValue("priority", dataSnapshot.getPriority(), snapshot);
|
||||||
|
|
||||||
|
eventMap.putInt("refId", refId);
|
||||||
|
if (listenerId != null) {
|
||||||
|
eventMap.putInt("listenerId", listenerId);
|
||||||
|
}
|
||||||
eventMap.putString("path", path);
|
eventMap.putString("path", path);
|
||||||
eventMap.putMap("snapshot", snapshot);
|
eventMap.putMap("snapshot", snapshot);
|
||||||
eventMap.putString("eventName", name);
|
eventMap.putString("eventName", name);
|
||||||
eventMap.putString("modifiersString", modifiersString);
|
|
||||||
|
|
||||||
return eventMap;
|
return eventMap;
|
||||||
}
|
}
|
||||||
|
|
|
@ -34,7 +34,7 @@ import io.invertase.firebase.Utils;
|
||||||
|
|
||||||
public class RNFirebaseDatabase extends ReactContextBaseJavaModule {
|
public class RNFirebaseDatabase extends ReactContextBaseJavaModule {
|
||||||
private static final String TAG = "RNFirebaseDatabase";
|
private static final String TAG = "RNFirebaseDatabase";
|
||||||
private HashMap<String, RNFirebaseDatabaseReference> mDBListeners = new HashMap<>();
|
private HashMap<Integer, RNFirebaseDatabaseReference> mReferences = new HashMap<>();
|
||||||
private HashMap<String, RNFirebaseTransactionHandler> mTransactionHandlers = new HashMap<>();
|
private HashMap<String, RNFirebaseTransactionHandler> mTransactionHandlers = new HashMap<>();
|
||||||
private FirebaseDatabase mFirebaseDatabase;
|
private FirebaseDatabase mFirebaseDatabase;
|
||||||
|
|
||||||
|
@ -279,61 +279,60 @@ public class RNFirebaseDatabase extends ReactContextBaseJavaModule {
|
||||||
}
|
}
|
||||||
|
|
||||||
@ReactMethod
|
@ReactMethod
|
||||||
public void on(final String path, final String modifiersString, final ReadableArray modifiersArray, final String eventName, final Callback callback) {
|
public void on(final int refId, final String path, final ReadableArray modifiers, final int listenerId, final String eventName, final Callback callback) {
|
||||||
RNFirebaseDatabaseReference ref = this.getDBHandle(path, modifiersArray, modifiersString);
|
RNFirebaseDatabaseReference ref = this.getDBHandle(refId, path, modifiers);
|
||||||
|
|
||||||
if (eventName.equals("value")) {
|
if (eventName.equals("value")) {
|
||||||
ref.addValueEventListener();
|
ref.addValueEventListener(listenerId);
|
||||||
} else {
|
} else {
|
||||||
ref.addChildEventListener(eventName);
|
ref.addChildEventListener(listenerId, eventName);
|
||||||
}
|
}
|
||||||
|
|
||||||
WritableMap resp = Arguments.createMap();
|
WritableMap resp = Arguments.createMap();
|
||||||
resp.putString("status", "success");
|
resp.putString("status", "success");
|
||||||
|
resp.putInt("refId", refId);
|
||||||
resp.putString("handle", path);
|
resp.putString("handle", path);
|
||||||
callback.invoke(null, resp);
|
callback.invoke(null, resp);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ReactMethod
|
@ReactMethod
|
||||||
public void once(final String path, final String modifiersString, final ReadableArray modifiersArray, final String eventName, final Callback callback) {
|
public void once(final int refId, final String path, final ReadableArray modifiers, final String eventName, final Callback callback) {
|
||||||
RNFirebaseDatabaseReference ref = this.getDBHandle(path, modifiersArray, modifiersString);
|
RNFirebaseDatabaseReference ref = this.getDBHandle(refId, path, modifiers);
|
||||||
ref.addOnceValueEventListener(callback);
|
ref.addOnceValueEventListener(callback);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* At the time of this writing, off() only gets called when there are no more subscribers to a given path.
|
* At the time of this writing, off() only gets called when there are no more subscribers to a given path.
|
||||||
* `mListeners` might therefore be out of sync (though javascript isnt listening for those eventTypes, so
|
* `mListeners` might therefore be out of sync (though javascript isnt listening for those eventNames, so
|
||||||
* it doesn't really matter- just polluting the RN bridge a little more than necessary.
|
* it doesn't really matter- just polluting the RN bridge a little more than necessary.
|
||||||
* off() should therefore clean *everything* up
|
* off() should therefore clean *everything* up
|
||||||
*/
|
*/
|
||||||
@ReactMethod
|
@ReactMethod
|
||||||
public void off(
|
public void off(
|
||||||
final String path,
|
final int refId,
|
||||||
final String modifiersString,
|
final ReadableArray listeners,
|
||||||
final String eventName,
|
|
||||||
final Callback callback) {
|
final Callback callback) {
|
||||||
|
|
||||||
String key = this.getDBListenerKey(path, modifiersString);
|
RNFirebaseDatabaseReference r = mReferences.get(refId);
|
||||||
RNFirebaseDatabaseReference r = mDBListeners.get(key);
|
|
||||||
|
|
||||||
if (r != null) {
|
if (r != null) {
|
||||||
if (eventName == null || "".equals(eventName)) {
|
List<Object> listenersList = Utils.recursivelyDeconstructReadableArray(listeners);
|
||||||
r.cleanup();
|
|
||||||
mDBListeners.remove(key);
|
for (Object l : listenersList) {
|
||||||
} else {
|
Map<String, Object> listener = (Map) l;
|
||||||
r.removeEventListener(eventName);
|
int listenerId = ((Double) listener.get("listenerId")).intValue();
|
||||||
|
String eventName = (String) listener.get("eventName");
|
||||||
|
r.removeEventListener(listenerId, eventName);
|
||||||
if (!r.hasListeners()) {
|
if (!r.hasListeners()) {
|
||||||
mDBListeners.remove(key);
|
mReferences.remove(refId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Log.d(TAG, "Removed listener " + path + "/" + modifiersString);
|
Log.d(TAG, "Removed listeners refId: " + refId + " ; count: " + listeners.size());
|
||||||
WritableMap resp = Arguments.createMap();
|
WritableMap resp = Arguments.createMap();
|
||||||
resp.putString("handle", path);
|
resp.putInt("refId", refId);
|
||||||
resp.putString("status", "success");
|
resp.putString("status", "success");
|
||||||
resp.putString("modifiersString", modifiersString);
|
|
||||||
//TODO: Remaining listeners
|
|
||||||
callback.invoke(null, resp);
|
callback.invoke(null, resp);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -440,23 +439,19 @@ public class RNFirebaseDatabase extends ReactContextBaseJavaModule {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private RNFirebaseDatabaseReference getDBHandle(final String path, final ReadableArray modifiersArray, final String modifiersString) {
|
private RNFirebaseDatabaseReference getDBHandle(final int refId, final String path,
|
||||||
String key = this.getDBListenerKey(path, modifiersString);
|
final ReadableArray modifiers) {
|
||||||
RNFirebaseDatabaseReference r = mDBListeners.get(key);
|
RNFirebaseDatabaseReference r = mReferences.get(refId);
|
||||||
|
|
||||||
if (r == null) {
|
if (r == null) {
|
||||||
ReactContext ctx = getReactApplicationContext();
|
ReactContext ctx = getReactApplicationContext();
|
||||||
r = new RNFirebaseDatabaseReference(ctx, mFirebaseDatabase, path, modifiersArray, modifiersString);
|
r = new RNFirebaseDatabaseReference(ctx, mFirebaseDatabase, refId, path, modifiers);
|
||||||
mDBListeners.put(key, r);
|
mReferences.put(refId, r);
|
||||||
}
|
}
|
||||||
|
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
|
|
||||||
private String getDBListenerKey(String path, String modifiersString) {
|
|
||||||
return path + " | " + modifiersString;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Map<String, Object> getConstants() {
|
public Map<String, Object> getConstants() {
|
||||||
final Map<String, Object> constants = new HashMap<>();
|
final Map<String, Object> constants = new HashMap<>();
|
||||||
|
|
|
@ -1,9 +1,11 @@
|
||||||
package io.invertase.firebase.database;
|
package io.invertase.firebase.database;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import android.util.Log;
|
import android.util.Log;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
import com.facebook.react.bridge.Callback;
|
import com.facebook.react.bridge.Callback;
|
||||||
|
@ -25,81 +27,87 @@ public class RNFirebaseDatabaseReference {
|
||||||
private static final String TAG = "RNFirebaseDBReference";
|
private static final String TAG = "RNFirebaseDBReference";
|
||||||
|
|
||||||
private Query mQuery;
|
private Query mQuery;
|
||||||
|
private int mRefId;
|
||||||
private String mPath;
|
private String mPath;
|
||||||
private String mModifiersString;
|
private Map<Integer, ChildEventListener> mChildEventListeners = new HashMap<>();
|
||||||
private ChildEventListener mEventListener;
|
private Map<Integer, ValueEventListener> mValueEventListeners = new HashMap<>();
|
||||||
private ValueEventListener mValueListener;
|
|
||||||
private ReactContext mReactContext;
|
private ReactContext mReactContext;
|
||||||
private Set<String> childEventListeners = new HashSet<>();
|
|
||||||
|
|
||||||
public RNFirebaseDatabaseReference(final ReactContext context,
|
public RNFirebaseDatabaseReference(final ReactContext context,
|
||||||
final FirebaseDatabase firebaseDatabase,
|
final FirebaseDatabase firebaseDatabase,
|
||||||
|
final int refId,
|
||||||
final String path,
|
final String path,
|
||||||
final ReadableArray modifiersArray,
|
final ReadableArray modifiersArray) {
|
||||||
final String modifiersString) {
|
|
||||||
mReactContext = context;
|
mReactContext = context;
|
||||||
|
mRefId = refId;
|
||||||
mPath = path;
|
mPath = path;
|
||||||
mModifiersString = modifiersString;
|
|
||||||
mQuery = this.buildDatabaseQueryAtPathAndModifiers(firebaseDatabase, path, modifiersArray);
|
mQuery = this.buildDatabaseQueryAtPathAndModifiers(firebaseDatabase, path, modifiersArray);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void addChildEventListener(final String eventName) {
|
public void addChildEventListener(final int listenerId, final String eventName) {
|
||||||
if (mEventListener == null) {
|
if (!mChildEventListeners.containsKey(listenerId)) {
|
||||||
mEventListener = new ChildEventListener() {
|
ChildEventListener childEventListener = new ChildEventListener() {
|
||||||
@Override
|
@Override
|
||||||
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
|
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
|
||||||
handleDatabaseEvent("child_added", dataSnapshot);
|
if ("child_added".equals(eventName)) {
|
||||||
|
handleDatabaseEvent("child_added", listenerId, dataSnapshot);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
|
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
|
||||||
handleDatabaseEvent("child_changed", dataSnapshot);
|
if ("child_changed".equals(eventName)) {
|
||||||
|
handleDatabaseEvent("child_changed", listenerId, dataSnapshot);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onChildRemoved(DataSnapshot dataSnapshot) {
|
public void onChildRemoved(DataSnapshot dataSnapshot) {
|
||||||
handleDatabaseEvent("child_removed", dataSnapshot);
|
if ("child_removed".equals(eventName)) {
|
||||||
|
handleDatabaseEvent("child_removed", listenerId, dataSnapshot);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
|
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
|
||||||
handleDatabaseEvent("child_moved", dataSnapshot);
|
if ("child_moved".equals(eventName)) {
|
||||||
|
handleDatabaseEvent("child_moved", listenerId, dataSnapshot);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onCancelled(DatabaseError error) {
|
public void onCancelled(DatabaseError error) {
|
||||||
removeChildEventListener();
|
removeChildEventListener(listenerId);
|
||||||
handleDatabaseError(error);
|
handleDatabaseError(listenerId, error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
mQuery.addChildEventListener(mEventListener);
|
mChildEventListeners.put(listenerId, childEventListener);
|
||||||
Log.d(TAG, "Added ChildEventListener for path: " + mPath + " with modifiers: "+ mModifiersString);
|
mQuery.addChildEventListener(childEventListener);
|
||||||
|
Log.d(TAG, "Added ChildEventListener for refId: " + mRefId + " listenerId: " + listenerId);
|
||||||
} else {
|
} else {
|
||||||
Log.w(TAG, "Trying to add duplicate ChildEventListener for path: " + mPath + " with modifiers: "+ mModifiersString);
|
Log.d(TAG, "ChildEventListener for refId: " + mRefId + " listenerId: " + listenerId + " already exists");
|
||||||
}
|
}
|
||||||
//Keep track of the events that the JS is interested in knowing about
|
|
||||||
childEventListeners.add(eventName);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void addValueEventListener() {
|
public void addValueEventListener(final int listenerId) {
|
||||||
if (mValueListener == null) {
|
if (!mValueEventListeners.containsKey(listenerId)) {
|
||||||
mValueListener = new ValueEventListener() {
|
ValueEventListener valueEventListener = new ValueEventListener() {
|
||||||
@Override
|
@Override
|
||||||
public void onDataChange(DataSnapshot dataSnapshot) {
|
public void onDataChange(DataSnapshot dataSnapshot) {
|
||||||
handleDatabaseEvent("value", dataSnapshot);
|
handleDatabaseEvent("value", listenerId, dataSnapshot);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onCancelled(DatabaseError error) {
|
public void onCancelled(DatabaseError error) {
|
||||||
removeValueEventListener();
|
removeValueEventListener(listenerId);
|
||||||
handleDatabaseError(error);
|
handleDatabaseError(listenerId, error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
mQuery.addValueEventListener(mValueListener);
|
mValueEventListeners.put(listenerId, valueEventListener);
|
||||||
Log.d(TAG, "Added ValueEventListener for path: " + mPath + " with modifiers: "+ mModifiersString);
|
mQuery.addValueEventListener(valueEventListener);
|
||||||
//this.setListeningTo(mPath, modifiersString, "value");
|
Log.d(TAG, "Added ValueEventListener for refId: " + mRefId + " listenerId: " + listenerId);
|
||||||
} else {
|
} else {
|
||||||
Log.w(TAG, "Trying to add duplicate ValueEventListener for path: " + mPath + " with modifiers: "+ mModifiersString);
|
Log.d(TAG, "ValueEventListener for refId: " + mRefId + " listenerId: " + listenerId + " already exists");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -107,63 +115,59 @@ public class RNFirebaseDatabaseReference {
|
||||||
final ValueEventListener onceValueEventListener = new ValueEventListener() {
|
final ValueEventListener onceValueEventListener = new ValueEventListener() {
|
||||||
@Override
|
@Override
|
||||||
public void onDataChange(DataSnapshot dataSnapshot) {
|
public void onDataChange(DataSnapshot dataSnapshot) {
|
||||||
WritableMap data = Utils.snapshotToMap("value", mPath, mModifiersString, dataSnapshot);
|
WritableMap data = Utils.snapshotToMap("value", mRefId, null, mPath, dataSnapshot);
|
||||||
callback.invoke(null, data);
|
callback.invoke(null, data);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onCancelled(DatabaseError error) {
|
public void onCancelled(DatabaseError error) {
|
||||||
WritableMap err = Arguments.createMap();
|
WritableMap err = Arguments.createMap();
|
||||||
|
err.putInt("refId", mRefId);
|
||||||
err.putString("path", mPath);
|
err.putString("path", mPath);
|
||||||
err.putInt("code", error.getCode());
|
err.putInt("code", error.getCode());
|
||||||
err.putString("modifiers", mModifiersString);
|
|
||||||
err.putString("details", error.getDetails());
|
err.putString("details", error.getDetails());
|
||||||
err.putString("message", error.getMessage());
|
err.putString("message", error.getMessage());
|
||||||
callback.invoke(err);
|
callback.invoke(err);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
mQuery.addListenerForSingleValueEvent(onceValueEventListener);
|
mQuery.addListenerForSingleValueEvent(onceValueEventListener);
|
||||||
Log.d(TAG, "Added OnceValueEventListener for path: " + mPath + " with modifiers " + mModifiersString);
|
Log.d(TAG, "Added OnceValueEventListener for refId: " + mRefId);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void removeEventListener(String eventName) {
|
public void removeEventListener(int listenerId, String eventName) {
|
||||||
if ("value".equals(eventName)) {
|
if ("value".equals(eventName)) {
|
||||||
this.removeValueEventListener();
|
this.removeValueEventListener(listenerId);
|
||||||
} else {
|
} else {
|
||||||
childEventListeners.remove(eventName);
|
this.removeChildEventListener(listenerId);
|
||||||
if (childEventListeners.isEmpty()) {
|
|
||||||
this.removeChildEventListener();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean hasListeners() {
|
public boolean hasListeners() {
|
||||||
return mEventListener != null || mValueListener != null;
|
return !mChildEventListeners.isEmpty() || !mValueEventListeners.isEmpty();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void cleanup() {
|
public void cleanup() {
|
||||||
Log.d(TAG, "cleaning up database reference " + this);
|
Log.d(TAG, "cleaning up database reference " + this);
|
||||||
childEventListeners.clear();
|
this.removeChildEventListener(null);
|
||||||
this.removeChildEventListener();
|
this.removeValueEventListener(null);
|
||||||
this.removeValueEventListener();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void removeChildEventListener() {
|
private void removeChildEventListener(Integer listenerId) {
|
||||||
if (mEventListener != null) {
|
ChildEventListener listener = mChildEventListeners.remove(listenerId);
|
||||||
mQuery.removeEventListener(mEventListener);
|
if (listener != null) {
|
||||||
mEventListener = null;
|
mQuery.removeEventListener(listener);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void removeValueEventListener() {
|
private void removeValueEventListener(Integer listenerId) {
|
||||||
if (mValueListener != null) {
|
ValueEventListener listener = mValueEventListeners.remove(listenerId);
|
||||||
mQuery.removeEventListener(mValueListener);
|
if (listener != null) {
|
||||||
mValueListener = null;
|
mQuery.removeEventListener(listener);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void handleDatabaseEvent(final String name, final DataSnapshot dataSnapshot) {
|
private void handleDatabaseEvent(final String name, final Integer listenerId, final DataSnapshot dataSnapshot) {
|
||||||
WritableMap data = Utils.snapshotToMap(name, mPath, mModifiersString, dataSnapshot);
|
WritableMap data = Utils.snapshotToMap(name, mRefId, listenerId, mPath, dataSnapshot);
|
||||||
WritableMap evt = Arguments.createMap();
|
WritableMap evt = Arguments.createMap();
|
||||||
evt.putString("eventName", name);
|
evt.putString("eventName", name);
|
||||||
evt.putMap("body", data);
|
evt.putMap("body", data);
|
||||||
|
@ -171,12 +175,15 @@ public class RNFirebaseDatabaseReference {
|
||||||
Utils.sendEvent(mReactContext, "database_event", evt);
|
Utils.sendEvent(mReactContext, "database_event", evt);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void handleDatabaseError(final DatabaseError error) {
|
private void handleDatabaseError(final Integer listenerId, final DatabaseError error) {
|
||||||
WritableMap errMap = Arguments.createMap();
|
WritableMap errMap = Arguments.createMap();
|
||||||
|
|
||||||
|
errMap.putInt("refId", mRefId);
|
||||||
|
if (listenerId != null) {
|
||||||
|
errMap.putInt("listenerId", listenerId);
|
||||||
|
}
|
||||||
errMap.putString("path", mPath);
|
errMap.putString("path", mPath);
|
||||||
errMap.putInt("code", error.getCode());
|
errMap.putInt("code", error.getCode());
|
||||||
errMap.putString("modifiers", mModifiersString);
|
|
||||||
errMap.putString("details", error.getDetails());
|
errMap.putString("details", error.getDetails());
|
||||||
errMap.putString("message", error.getMessage());
|
errMap.putString("message", error.getMessage());
|
||||||
|
|
||||||
|
@ -187,104 +194,102 @@ public class RNFirebaseDatabaseReference {
|
||||||
final String path,
|
final String path,
|
||||||
final ReadableArray modifiers) {
|
final ReadableArray modifiers) {
|
||||||
Query query = firebaseDatabase.getReference(path);
|
Query query = firebaseDatabase.getReference(path);
|
||||||
List<Object> strModifiers = Utils.recursivelyDeconstructReadableArray(modifiers);
|
List<Object> modifiersList = Utils.recursivelyDeconstructReadableArray(modifiers);
|
||||||
|
|
||||||
for (Object strModifier : strModifiers) {
|
for (Object m : modifiersList) {
|
||||||
String str = (String) strModifier;
|
Map<String, Object> modifier = (Map) m;
|
||||||
|
String type = (String) modifier.get("type");
|
||||||
|
String name = (String) modifier.get("name");
|
||||||
|
|
||||||
String[] strArr = str.split(":");
|
if ("orderBy".equals(type)) {
|
||||||
String methStr = strArr[0];
|
if ("orderByKey".equals(name)) {
|
||||||
|
|
||||||
if (methStr.equalsIgnoreCase("orderByKey")) {
|
|
||||||
query = query.orderByKey();
|
query = query.orderByKey();
|
||||||
} else if (methStr.equalsIgnoreCase("orderByValue")) {
|
} else if ("orderByPriority".equals(name)) {
|
||||||
query = query.orderByValue();
|
|
||||||
} else if (methStr.equalsIgnoreCase("orderByPriority")) {
|
|
||||||
query = query.orderByPriority();
|
query = query.orderByPriority();
|
||||||
} else if (methStr.contains("orderByChild")) {
|
} else if ("orderByValue".equals(name)) {
|
||||||
String key = strArr[1];
|
query = query.orderByValue();
|
||||||
Log.d(TAG, "orderByChild: " + key);
|
} else if ("orderByChild".equals(name)) {
|
||||||
|
String key = (String) modifier.get("key");
|
||||||
query = query.orderByChild(key);
|
query = query.orderByChild(key);
|
||||||
} else if (methStr.contains("limitToLast")) {
|
}
|
||||||
String key = strArr[1];
|
} else if ("limit".equals(type)) {
|
||||||
int limit = Integer.parseInt(key);
|
int limit = (Integer) modifier.get("limit");
|
||||||
Log.d(TAG, "limitToLast: " + limit);
|
if ("limitToLast".equals(name)) {
|
||||||
query = query.limitToLast(limit);
|
query = query.limitToLast(limit);
|
||||||
} else if (methStr.contains("limitToFirst")) {
|
} else if ("limitToFirst".equals(name)) {
|
||||||
String key = strArr[1];
|
|
||||||
int limit = Integer.parseInt(key);
|
|
||||||
Log.d(TAG, "limitToFirst: " + limit);
|
|
||||||
query = query.limitToFirst(limit);
|
query = query.limitToFirst(limit);
|
||||||
} else if (methStr.contains("equalTo")) {
|
|
||||||
String value = strArr[1];
|
|
||||||
String type = strArr[2];
|
|
||||||
if ("number".equals(type)) {
|
|
||||||
double doubleValue = Double.parseDouble(value);
|
|
||||||
if (strArr.length > 3) {
|
|
||||||
query = query.equalTo(doubleValue, strArr[3]);
|
|
||||||
} else {
|
|
||||||
query = query.equalTo(doubleValue);
|
|
||||||
}
|
}
|
||||||
} else if ("boolean".equals(type)) {
|
} else if ("filter".equals(type)) {
|
||||||
boolean booleanValue = Boolean.parseBoolean(value);
|
String valueType = (String) modifier.get("valueType");
|
||||||
if (strArr.length > 3) {
|
String key = (String) modifier.get("key");
|
||||||
query = query.equalTo(booleanValue, strArr[3]);
|
if ("equalTo".equals(name)) {
|
||||||
} else {
|
if ("number".equals(valueType)) {
|
||||||
query = query.equalTo(booleanValue);
|
double value = (Double) modifier.get("value");
|
||||||
}
|
if (key == null) {
|
||||||
} else {
|
|
||||||
if (strArr.length > 3) {
|
|
||||||
query = query.equalTo(value, strArr[3]);
|
|
||||||
} else {
|
|
||||||
query = query.equalTo(value);
|
query = query.equalTo(value);
|
||||||
|
} else {
|
||||||
|
query = query.equalTo(value, key);
|
||||||
|
}
|
||||||
|
} else if ("boolean".equals(valueType)) {
|
||||||
|
boolean value = (Boolean) modifier.get("value");
|
||||||
|
if (key == null) {
|
||||||
|
query = query.equalTo(value);
|
||||||
|
} else {
|
||||||
|
query = query.equalTo(value, key);
|
||||||
|
}
|
||||||
|
} else if ("string".equals(valueType)) {
|
||||||
|
String value = (String) modifier.get("value");
|
||||||
|
if (key == null) {
|
||||||
|
query = query.equalTo(value);
|
||||||
|
} else {
|
||||||
|
query = query.equalTo(value, key);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if (methStr.contains("endAt")) {
|
} else if ("endAt".equals(name)) {
|
||||||
String value = strArr[1];
|
if ("number".equals(valueType)) {
|
||||||
String type = strArr[2];
|
double value = (Double) modifier.get("value");
|
||||||
if ("number".equals(type)) {
|
if (key == null) {
|
||||||
double doubleValue = Double.parseDouble(value);
|
query = query.equalTo(value);
|
||||||
if (strArr.length > 3) {
|
|
||||||
query = query.endAt(doubleValue, strArr[3]);
|
|
||||||
} else {
|
} else {
|
||||||
query = query.endAt(doubleValue);
|
query = query.equalTo(value, key);
|
||||||
}
|
}
|
||||||
} else if ("boolean".equals(type)) {
|
} else if ("boolean".equals(valueType)) {
|
||||||
boolean booleanValue = Boolean.parseBoolean(value);
|
boolean value = (Boolean) modifier.get("value");
|
||||||
if (strArr.length > 3) {
|
if (key == null) {
|
||||||
query = query.endAt(booleanValue, strArr[3]);
|
query = query.equalTo(value);
|
||||||
} else {
|
} else {
|
||||||
query = query.endAt(booleanValue);
|
query = query.equalTo(value, key);
|
||||||
}
|
}
|
||||||
|
} else if ("string".equals(valueType)) {
|
||||||
|
String value = (String) modifier.get("value");
|
||||||
|
if (key == null) {
|
||||||
|
query = query.equalTo(value);
|
||||||
} else {
|
} else {
|
||||||
if (strArr.length > 3) {
|
query = query.equalTo(value, key);
|
||||||
query = query.endAt(value, strArr[3]);
|
|
||||||
} else {
|
|
||||||
query = query.endAt(value);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if (methStr.contains("startAt")) {
|
} else if ("startAt".equals(name)) {
|
||||||
String value = strArr[1];
|
if ("number".equals(valueType)) {
|
||||||
String type = strArr[2];
|
double value = (Double) modifier.get("value");
|
||||||
if ("number".equals(type)) {
|
if (key == null) {
|
||||||
double doubleValue = Double.parseDouble(value);
|
query = query.equalTo(value);
|
||||||
if (strArr.length > 3) {
|
|
||||||
query = query.startAt(doubleValue, strArr[3]);
|
|
||||||
} else {
|
} else {
|
||||||
query = query.startAt(doubleValue);
|
query = query.equalTo(value, key);
|
||||||
}
|
}
|
||||||
} else if ("boolean".equals(type)) {
|
} else if ("boolean".equals(valueType)) {
|
||||||
boolean booleanValue = Boolean.parseBoolean(value);
|
boolean value = (Boolean) modifier.get("value");
|
||||||
if (strArr.length > 3) {
|
if (key == null) {
|
||||||
query = query.startAt(booleanValue, strArr[3]);
|
query = query.equalTo(value);
|
||||||
} else {
|
} else {
|
||||||
query = query.startAt(booleanValue);
|
query = query.equalTo(value, key);
|
||||||
}
|
}
|
||||||
|
} else if ("string".equals(valueType)) {
|
||||||
|
String value = (String) modifier.get("value");
|
||||||
|
if (key == null) {
|
||||||
|
query = query.equalTo(value);
|
||||||
} else {
|
} else {
|
||||||
if (strArr.length > 3) {
|
query = query.equalTo(value, key);
|
||||||
query = query.startAt(value, strArr[3]);
|
}
|
||||||
} else {
|
|
||||||
query = query.startAt(value);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,25 @@
|
||||||
|
|
||||||
|
<h1 align="center">
|
||||||
|
<img src="https://camo.githubusercontent.com/6c827e5a0bb91259f82a1f4923ab7efa4891b119/687474703a2f2f692e696d6775722e636f6d2f303158514c30782e706e67"/><br>
|
||||||
|
|
||||||
|
React Native Firebase
|
||||||
|
</h1>
|
||||||
|
|
||||||
|
<div style="text-align: center;">
|
||||||
|
[![Chat](https://img.shields.io/badge/chat-on%20discord-7289da.svg)](https://discord.gg/t6bdqMs)
|
||||||
|
[![Gitter](https://badges.gitter.im/invertase/react-native-firebase.svg)](https://gitter.im/invertase/react-native-firebase?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
|
||||||
|
[![npm version](https://img.shields.io/npm/v/react-native-firebase.svg)](https://www.npmjs.com/package/react-native-firebase)
|
||||||
|
[![License](https://img.shields.io/npm/l/react-native-firebase.svg)](/LICENSE)
|
||||||
|
<br />
|
||||||
|
A well tested Firebase implementation for React Native, supporting both iOS & Android apps.
|
||||||
|
</div>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
RNFirebase is a _light-weight_ layer sitting on-top of the native Firebase libraries for both iOS and Android which mirrors the Firebase Web SDK as closely as possible.
|
||||||
|
|
||||||
|
Although the [Firebase Web SDK](https://www.npmjs.com/package/firebase) library will work with React Native, it is mainly built for the web.
|
||||||
|
|
||||||
|
RNFirebase provides a JavaScript bridge to the native Firebase SDKs for both iOS and Android. Firebase will run on the native thread, allowing the rest of your app to run on the [JS thread](https://facebook.github.io/react-native/docs/performance.html#javascript-frame-rate). The Firebase Web SDK also runs on the JS thread, therefore potentially affecting the frame rate causing jank with animations, touch events etc. All in all, RNFirebase provides much faster performance (~2x) over the web SDK.
|
||||||
|
|
||||||
|
The native SDKs also allow us to hook into device sdk's which are not possible with the web SDK, for example crash reporting, offline realtime database support, analyics and more!
|
|
@ -0,0 +1,25 @@
|
||||||
|
- Getting started
|
||||||
|
- [Installation - iOS](/installation-ios)
|
||||||
|
- [Installation - Android](/installation-android)
|
||||||
|
- [Firebase Setup](/firebase-setup.md)
|
||||||
|
- [Usage](/usage)
|
||||||
|
|
||||||
|
- Contributing
|
||||||
|
- [Guidelines](/contributing/guidelines)
|
||||||
|
- [Testing](/contributing/testing)
|
||||||
|
|
||||||
|
- Modules
|
||||||
|
- [Authentication](/modules/authentication)
|
||||||
|
- [Realtime Database](/modules/database)
|
||||||
|
- [Analytics](/modules/analytics)
|
||||||
|
- [Storage](/modules/storage)
|
||||||
|
- [Cloud Messaging](/modules/cloud-messaging)
|
||||||
|
- [Crash Reporting](/modules/crash)
|
||||||
|
- [Transactions](/modules/transactions)
|
||||||
|
|
||||||
|
- Other
|
||||||
|
- [Project Board](https://github.com/invertase/react-native-firebase/projects)
|
||||||
|
- [FAQs / Troubleshooting](/faqs)
|
||||||
|
- [Examples](https://github.com/invertase/react-native-firebase-examples)
|
||||||
|
- [Chat](https://discord.gg/t6bdqMs)
|
||||||
|
- [Gitter](https://gitter.im/invertase/react-native-firebase)
|
|
@ -1 +0,0 @@
|
||||||
# Remote Config
|
|
|
@ -0,0 +1,5 @@
|
||||||
|
# Guidelines
|
||||||
|
|
||||||
|
We welcome any contribution to the repository. Please ensure your changes to the JavaScript code follow the styling guides controlled by ESlint. Changes to native code should be kept clean and follow the standard of existing code.
|
||||||
|
|
||||||
|
Changes to existing code should ensure all relevant tests on the test app pass. Any new features should have new tests created and ensure all existing tests pass.
|
|
@ -0,0 +1,3 @@
|
||||||
|
# Testing
|
||||||
|
|
||||||
|
|
12
docs/faqs.md
12
docs/faqs.md
|
@ -1,6 +1,6 @@
|
||||||
# FAQs / Troubleshooting
|
# FAQs / Troubleshooting
|
||||||
|
|
||||||
### Comparison to Firestack
|
## Comparison to Firestack
|
||||||
|
|
||||||
Firestack was a great start to integrating Firebase and React Native, however has underlying issues which needed to be fixed.
|
Firestack was a great start to integrating Firebase and React Native, however has underlying issues which needed to be fixed.
|
||||||
A V3 fork of Firestack was created to help address issues such as lack of standardisation with the Firebase Web SDK,
|
A V3 fork of Firestack was created to help address issues such as lack of standardisation with the Firebase Web SDK,
|
||||||
|
@ -10,7 +10,7 @@ too large to manage on the existing repository, whilst trying to maintain backwa
|
||||||
RNFirebase was re-written from the ground up, addressing these issues with core focus being around matching the Web SDK as
|
RNFirebase was re-written from the ground up, addressing these issues with core focus being around matching the Web SDK as
|
||||||
closely as possible and fixing the major bugs/issues along the way.
|
closely as possible and fixing the major bugs/issues along the way.
|
||||||
|
|
||||||
### How do I integrate Redux with RNFirebase
|
## How do I integrate Redux with RNFirebase
|
||||||
|
|
||||||
As every project has different requirements & structure, RNFirebase *currently* has no built in methods for Redux integration.
|
As every project has different requirements & structure, RNFirebase *currently* has no built in methods for Redux integration.
|
||||||
As RNFirebase can be used outside of a Components context, you do have free reign to integrate it as you see fit. For example,
|
As RNFirebase can be used outside of a Components context, you do have free reign to integrate it as you see fit. For example,
|
||||||
|
@ -42,7 +42,7 @@ export function onAuthStateChanged() {
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### [Android] Google Play Services related issues
|
## [Android] Google Play Services related issues
|
||||||
|
|
||||||
The firebase SDK requires a certain version of Google Play Services installed on Android in order to function properly.
|
The firebase SDK requires a certain version of Google Play Services installed on Android in order to function properly.
|
||||||
|
|
||||||
|
@ -68,7 +68,7 @@ party emulator such as GenyMotion.
|
||||||
Using this kind of workaround with Google Play Services can be problematic, so we
|
Using this kind of workaround with Google Play Services can be problematic, so we
|
||||||
recommend using the native Android Studio emulators to reduce the chance of these complications.
|
recommend using the native Android Studio emulators to reduce the chance of these complications.
|
||||||
|
|
||||||
### [Android] Turning off Google Play Services availability errors
|
## [Android] Turning off Google Play Services availability errors
|
||||||
|
|
||||||
G.P.S errors can be turned off using a config option like so:
|
G.P.S errors can be turned off using a config option like so:
|
||||||
|
|
||||||
|
@ -79,7 +79,7 @@ const firebase = RNFirebase.initializeApp({
|
||||||
```
|
```
|
||||||
This will stop your app from immediately red-boxing or crashing, but won't solve the underlying issue of G.P.S not being available or of the correct version. This will mean certain functionalities won't work properly and your app may even crash.
|
This will stop your app from immediately red-boxing or crashing, but won't solve the underlying issue of G.P.S not being available or of the correct version. This will mean certain functionalities won't work properly and your app may even crash.
|
||||||
|
|
||||||
### [Android] Checking for Google Play Services availability with React Native Firebase
|
## [Android] Checking for Google Play Services availability with React Native Firebase
|
||||||
|
|
||||||
React Native Firebase actually has a useful helper object for checking G.P.S availability:
|
React Native Firebase actually has a useful helper object for checking G.P.S availability:
|
||||||
|
|
||||||
|
@ -109,7 +109,7 @@ This error will match the messages and error codes mentioned above, and can be f
|
||||||
https://developers.google.com/android/reference/com/google/android/gms/common/ConnectionResult#SERVICE_VERSION_UPDATE_REQUIRED
|
https://developers.google.com/android/reference/com/google/android/gms/common/ConnectionResult#SERVICE_VERSION_UPDATE_REQUIRED
|
||||||
|
|
||||||
|
|
||||||
### [Android] Duplicate Dex Files error (build time error)
|
## [Android] Duplicate Dex Files error (build time error)
|
||||||
|
|
||||||
A common build time error when using libraries that require google play services is of the form:
|
A common build time error when using libraries that require google play services is of the form:
|
||||||
'Failed on android with com.android.dex.DexException: Multiple dex files... '
|
'Failed on android with com.android.dex.DexException: Multiple dex files... '
|
||||||
|
|
|
@ -10,45 +10,11 @@ Each platform uses a different setup method after creating the project.
|
||||||
|
|
||||||
## iOS
|
## iOS
|
||||||
|
|
||||||
See the [ios setup guide](./installation.ios.md).
|
For iOS, ensure you've followed the instructions provided by Firebase; adding your [GoogleService-Info.plist](https://github.com/invertase/react-native-firebase/blob/master/tests/ios/GoogleService-Info.plist)
|
||||||
|
file to the project, and [configuring your AppDelegate](https://github.com/invertase/react-native-firebase/blob/master/tests/ios/ReactNativeFirebaseDemo/AppDelegate.m#L20).
|
||||||
|
|
||||||
## Android
|
## Android
|
||||||
|
|
||||||
See the [android setup guide](./installation.android.md).
|
For Android, ensure you've followed the instructions provided by Firebase; adding your [google-services.json](https://github.com/invertase/react-native-firebase/blob/master/tests/android/app/google-services.json)
|
||||||
|
file to the project, installing the [google-services](https://github.com/invertase/react-native-firebase/blob/master/tests/android/build.gradle#L9)
|
||||||
## Usage
|
plugin and applying **at the end** of your [`build.gradle`](https://github.com/invertase/react-native-firebase/blob/master/tests/android/app/build.gradle#L144).
|
||||||
|
|
||||||
After creating a Firebase project and installing the library, we can use it in our project by importing the library in our JavaScript:
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
import RNFirebase from 'react-native-firebase'
|
|
||||||
```
|
|
||||||
|
|
||||||
We need to tell the Firebase library we want to _configure_ the project. RNFirebase provides a way to configure both the native and the JavaScript side of the project at the same time with a single command:
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const firebase = RNFirebase.initializeApp({
|
|
||||||
// config options
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
### Configuration Options
|
|
||||||
|
|
||||||
| option | type | Default Value | Description |
|
|
||||||
|----------------|----------|-------------------------|----------------------------------------|
|
|
||||||
| debug | bool | false | When set to true, RNFirebase will log messages to the console and fire `debug` events we can listen to in `js` |
|
|
||||||
| persistence | bool | false | When set to true, database persistence will be enabled. |
|
|
||||||
|
|
||||||
For instance:
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
import RNFirebase from 'react-native-firebase';
|
|
||||||
|
|
||||||
const configurationOptions = {
|
|
||||||
debug: true
|
|
||||||
};
|
|
||||||
|
|
||||||
const firebase = RNFirebase.initializeApp(configurationOptions);
|
|
||||||
|
|
||||||
export default firebase;
|
|
||||||
```
|
|
||||||
|
|
|
@ -0,0 +1,46 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>react-native-firebase - A react native firebase library supporting both android and ios native firebase SDK's</title>
|
||||||
|
<meta name="description" content="A react native firebase library supporting both android and ios native firebase SDK's">
|
||||||
|
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
|
||||||
|
<link rel="shortcut icon" type="image/png" href="https://camo.githubusercontent.com/6c827e5a0bb91259f82a1f4923ab7efa4891b119/687474703a2f2f692e696d6775722e636f6d2f303158514c30782e706e67"/>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="app"></div>
|
||||||
|
</body>
|
||||||
|
<script>
|
||||||
|
window.$docsify = {
|
||||||
|
name: 'react-native-firebase',
|
||||||
|
repo: 'https://github.com/invertase/react-native-firebase',
|
||||||
|
loadSidebar: true,
|
||||||
|
search: 'auto',
|
||||||
|
themeColor: '#f5820b',
|
||||||
|
subMaxLevel: 2,
|
||||||
|
maxLevel: 4,
|
||||||
|
ga: 'UA-98196653-1',
|
||||||
|
plugins: [
|
||||||
|
function (hook) {
|
||||||
|
var footer = [
|
||||||
|
'<hr/>',
|
||||||
|
'<footer>',
|
||||||
|
`<span>Caught a mistake or want to contribute to the documentation? <a href="https://github.com/invertase/react-native-firebase/tree/master/docs" target="_blank">Edit documentation on Github!</a>.</span>`,
|
||||||
|
'</footer>'
|
||||||
|
].join('');
|
||||||
|
|
||||||
|
hook.afterEach(function (html) {
|
||||||
|
return html + footer
|
||||||
|
})
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
<script src="//unpkg.com/docsify/lib/docsify.min.js"></script>
|
||||||
|
<script src="//unpkg.com/docsify/lib/plugins/search.js"></script>
|
||||||
|
<link rel="stylesheet" href="//unpkg.com/docsify/themes/vue.css">
|
||||||
|
<script src="//unpkg.com/docsify/lib/plugins/emoji.min.js"></script>
|
||||||
|
<script src="//unpkg.com/docsify/lib/plugins/ga.min.js"></script>
|
||||||
|
<script src="//unpkg.com/prismjs/components/prism-bash.min.js"></script>
|
||||||
|
<script src="//unpkg.com/prismjs/components/prism-javascript.min.js"></script>
|
||||||
|
</html>
|
|
@ -1,6 +1,6 @@
|
||||||
# Android Installation
|
# Android Installation
|
||||||
|
|
||||||
### 1 - Setup google-services.json
|
## 1) Setup google-services.json
|
||||||
Download the `google-services.json` file provided by Firebase in the _Add Firebase to Android_ platform menu in your Firebase configuration console. This file should be downloaded to `YOUR_PROJECT/android/app/google-services.json`.
|
Download the `google-services.json` file provided by Firebase in the _Add Firebase to Android_ platform menu in your Firebase configuration console. This file should be downloaded to `YOUR_PROJECT/android/app/google-services.json`.
|
||||||
|
|
||||||
Next you'll have to add the google-services gradle plugin in order to parse it.
|
Next you'll have to add the google-services gradle plugin in order to parse it.
|
||||||
|
@ -23,7 +23,7 @@ In your app build.gradle file, add the gradle plugin at the VERY BOTTOM of the f
|
||||||
apply plugin: 'com.google.gms.google-services'
|
apply plugin: 'com.google.gms.google-services'
|
||||||
```
|
```
|
||||||
|
|
||||||
### 2 - Link RNFirebase
|
## 2) Link RNFirebase
|
||||||
|
|
||||||
To install `react-native-firebase` in your project, you'll need to import the package from `io.invertase.firebase` in your project's `android/app/src/main/java/com/[app name]/MainApplication.java` and list it as a package for ReactNative in the `getPackages()` function:
|
To install `react-native-firebase` in your project, you'll need to import the package from `io.invertase.firebase` in your project's `android/app/src/main/java/com/[app name]/MainApplication.java` and list it as a package for ReactNative in the `getPackages()` function:
|
||||||
|
|
||||||
|
@ -61,7 +61,7 @@ include ':react-native-firebase'
|
||||||
project(':react-native-firebase').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-firebase/android')
|
project(':react-native-firebase').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-firebase/android')
|
||||||
```
|
```
|
||||||
|
|
||||||
### 3 - Cloud Messaging (optional)
|
## 3) Cloud Messaging (optional)
|
||||||
|
|
||||||
If you plan on using [Firebase Cloud Messaging](https://firebase.google.com/docs/cloud-messaging/), add the following to `android/app/src/main/AndroidManifest.xml`.
|
If you plan on using [Firebase Cloud Messaging](https://firebase.google.com/docs/cloud-messaging/), add the following to `android/app/src/main/AndroidManifest.xml`.
|
||||||
|
|
|
@ -1,9 +1,9 @@
|
||||||
## iOS Installation
|
# iOS Installation
|
||||||
|
|
||||||
### 1 - Setup google-services.plist and dependencies
|
## 1) Setup google-services.plist and dependencies
|
||||||
Setup the `google-services.plist` file and Firebase ios frameworks first; check out the relevant Firebase docs [here](https://firebase.google.com/docs/ios/setup#frameworks).
|
Setup the `google-services.plist` file and Firebase ios frameworks first; check out the relevant Firebase docs [here](https://firebase.google.com/docs/ios/setup#frameworks).
|
||||||
|
|
||||||
#### 1.1 - Initialisation
|
### 1.1) Initialisation
|
||||||
Make sure you've added the following to the top of your `ios/[YOUR APP NAME]]/AppDelegate.m` file:
|
Make sure you've added the following to the top of your `ios/[YOUR APP NAME]]/AppDelegate.m` file:
|
||||||
|
|
||||||
`#import <Firebase.h>`
|
`#import <Firebase.h>`
|
||||||
|
@ -12,10 +12,10 @@ and this to the `didFinishLaunchingWithOptions:(NSDictionary *)launchOptions` me
|
||||||
|
|
||||||
`[FIRApp configure];`
|
`[FIRApp configure];`
|
||||||
|
|
||||||
### 2 - Link RNFirebase
|
## 2) Link RNFirebase
|
||||||
There are multiple ways to install RNFirebase depending on how your project is currently setup:
|
There are multiple ways to install RNFirebase depending on how your project is currently setup:
|
||||||
|
|
||||||
#### 2.1 - Existing Cocoapods setup, including React Native as a pod
|
### 2.1) Existing Cocoapods setup, including React Native as a pod
|
||||||
Simply add the following to your `Podfile`:
|
Simply add the following to your `Podfile`:
|
||||||
|
|
||||||
```ruby
|
```ruby
|
||||||
|
@ -33,7 +33,7 @@ pod 'Firebase/Storage'
|
||||||
pod 'RNFirebase', :path => '../node_modules/react-native-firebase'
|
pod 'RNFirebase', :path => '../node_modules/react-native-firebase'
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 2.2 - Via react-native-cli link
|
### 2.2) Via react-native-cli link
|
||||||
React native ships with a `link` command that can be used to link the projects together, which can help automate the process of linking our package environments.
|
React native ships with a `link` command that can be used to link the projects together, which can help automate the process of linking our package environments.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
@ -46,12 +46,13 @@ Update the newly installed pods once the linking is done:
|
||||||
cd ios && pod update --verbose
|
cd ios && pod update --verbose
|
||||||
```
|
```
|
||||||
|
|
||||||
##### cocoapods
|
### cocoapods
|
||||||
|
|
||||||
We've automated the process of setting up with cocoapods. This will happen automatically upon linking the package with `react-native-cli`.
|
We've automated the process of setting up with cocoapods. This will happen automatically upon linking the package with `react-native-cli`.
|
||||||
|
|
||||||
**Remember to use the `ios/[YOUR APP NAME].xcworkspace` instead of the `ios/[YOUR APP NAME].xcproj` file from now on**.
|
> Remember to use the `ios/[YOUR APP NAME].xcworkspace` instead of the `ios/[YOUR APP NAME].xcproj` file from now on.
|
||||||
|
|
||||||
#### 2.3 - Manually
|
### 2.3) Manually
|
||||||
|
|
||||||
If you prefer not to use `react-native link`, we can manually link the package together with the following steps, after `npm install`:
|
If you prefer not to use `react-native link`, we can manually link the package together with the following steps, after `npm install`:
|
||||||
|
|
|
@ -72,7 +72,7 @@ class MyComponent extends Component {
|
||||||
|
|
||||||
### Reading data
|
### Reading data
|
||||||
|
|
||||||
Firstack allows the database instance to [persist on disk](https://firebase.google.com/docs/database/android/offline-capabilities) if enabled.
|
Firebase allows the database instance to [persist on disk](https://firebase.google.com/docs/database/android/offline-capabilities) if enabled.
|
||||||
To enable database persistence, pass the configuration option `persistence` before calls are made:
|
To enable database persistence, pass the configuration option `persistence` before calls are made:
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
|
@ -181,7 +181,7 @@ class ToDos extends Component {
|
||||||
#### Differences between `.on` & `.once`
|
#### Differences between `.on` & `.once`
|
||||||
|
|
||||||
With persistence enabled, any calls to a ref with `.once` will always read the data from disk and not contact the server.
|
With persistence enabled, any calls to a ref with `.once` will always read the data from disk and not contact the server.
|
||||||
On behavious differently, by first checking for a connection and if none exists returns the persisted data. If it successfully connects
|
On behaves differently, by first checking for a connection and if none exists returns the persisted data. If it successfully connects
|
||||||
to the server, the new data will be returned and the disk data will be updated.
|
to the server, the new data will be returned and the disk data will be updated.
|
||||||
|
|
||||||
The database refs has a `keepSynced()` function to tell the RNFirebase library to keep the data at the `ref` in sync.
|
The database refs has a `keepSynced()` function to tell the RNFirebase library to keep the data at the `ref` in sync.
|
|
@ -3,8 +3,6 @@
|
||||||
RNFirebase mimics the [Web Firebase SDK Storage](https://firebase.google.com/docs/storage/web/start), whilst
|
RNFirebase mimics the [Web Firebase SDK Storage](https://firebase.google.com/docs/storage/web/start), whilst
|
||||||
providing some iOS and Android specific functionality.
|
providing some iOS and Android specific functionality.
|
||||||
|
|
||||||
All Storage operations are accessed via `storage()`.
|
|
||||||
|
|
||||||
## Uploading files
|
## Uploading files
|
||||||
|
|
||||||
### Simple
|
### Simple
|
|
@ -1,6 +1,6 @@
|
||||||
# Transactions
|
# Transactions
|
||||||
|
|
||||||
Transactions are currently an experimental feature as they can not be integrated as easily as the other Firebase features. Please see the [Firebase documentation](https://firebase.google.com/docs/reference/js/firebase.database.Reference#transaction) for full implemtation details.
|
> Transactions are currently an experimental feature as they can not be integrated as easily as the other Firebase features. Please see the [Firebase documentation](https://firebase.google.com/docs/reference/js/firebase.database.Reference#transaction) for full implemtation details.
|
||||||
|
|
||||||
## Example
|
## Example
|
||||||
|
|
|
@ -0,0 +1,36 @@
|
||||||
|
# Usage
|
||||||
|
|
||||||
|
After creating a Firebase project and installing the library, we can use it in our project by importing the library in our JavaScript:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
import RNFirebase from 'react-native-firebase'
|
||||||
|
```
|
||||||
|
|
||||||
|
We need to tell the Firebase library we want to _configure_ the project. RNFirebase provides a way to configure both the native and the JavaScript side of the project at the same time with a single command:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const firebase = RNFirebase.initializeApp({
|
||||||
|
// config options
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## Configuration Options
|
||||||
|
|
||||||
|
| option | type | Default Value | Description |
|
||||||
|
|----------------|----------|-------------------------|----------------------------------------|
|
||||||
|
| debug | bool | false | When set to true, RNFirebase will log messages to the console and fire `debug` events we can listen to in `js` |
|
||||||
|
| persistence | bool | false | When set to true, database persistence will be enabled. |
|
||||||
|
|
||||||
|
For instance:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
import RNFirebase from 'react-native-firebase';
|
||||||
|
|
||||||
|
const configurationOptions = {
|
||||||
|
debug: true
|
||||||
|
};
|
||||||
|
|
||||||
|
const firebase = RNFirebase.initializeApp(configurationOptions);
|
||||||
|
|
||||||
|
export default firebase;
|
||||||
|
```
|
|
@ -5,64 +5,61 @@
|
||||||
@interface RNFirebaseDBReference : NSObject
|
@interface RNFirebaseDBReference : NSObject
|
||||||
@property RCTEventEmitter *emitter;
|
@property RCTEventEmitter *emitter;
|
||||||
@property FIRDatabaseQuery *query;
|
@property FIRDatabaseQuery *query;
|
||||||
|
@property NSNumber *refId;
|
||||||
@property NSString *path;
|
@property NSString *path;
|
||||||
@property NSString *modifiersString;
|
|
||||||
@property NSMutableDictionary *listeners;
|
@property NSMutableDictionary *listeners;
|
||||||
@property FIRDatabaseHandle childAddedHandler;
|
|
||||||
@property FIRDatabaseHandle childModifiedHandler;
|
|
||||||
@property FIRDatabaseHandle childRemovedHandler;
|
|
||||||
@property FIRDatabaseHandle childMovedHandler;
|
|
||||||
@property FIRDatabaseHandle childValueHandler;
|
|
||||||
+ (NSDictionary *) snapshotToDict:(FIRDataSnapshot *) snapshot;
|
+ (NSDictionary *) snapshotToDict:(FIRDataSnapshot *) snapshot;
|
||||||
@end
|
@end
|
||||||
|
|
||||||
@implementation RNFirebaseDBReference
|
@implementation RNFirebaseDBReference
|
||||||
|
|
||||||
|
|
||||||
- (id) initWithPathAndModifiers:(RCTEventEmitter *) emitter
|
- (id) initWithPathAndModifiers:(RCTEventEmitter *) emitter
|
||||||
database:(FIRDatabase *) database
|
database:(FIRDatabase *) database
|
||||||
|
refId:(NSNumber *) refId
|
||||||
path:(NSString *) path
|
path:(NSString *) path
|
||||||
modifiers:(NSArray *) modifiers
|
modifiers:(NSArray *) modifiers
|
||||||
modifiersString:(NSString *) modifiersString
|
|
||||||
{
|
{
|
||||||
self = [super init];
|
self = [super init];
|
||||||
if (self) {
|
if (self) {
|
||||||
_emitter = emitter;
|
_emitter = emitter;
|
||||||
|
_refId = refId;
|
||||||
_path = path;
|
_path = path;
|
||||||
_modifiersString = modifiersString;
|
|
||||||
_query = [self buildQueryAtPathWithModifiers:database path:path modifiers:modifiers];
|
_query = [self buildQueryAtPathWithModifiers:database path:path modifiers:modifiers];
|
||||||
_listeners = [[NSMutableDictionary alloc] init];
|
_listeners = [[NSMutableDictionary alloc] init];
|
||||||
}
|
}
|
||||||
return self;
|
return self;
|
||||||
}
|
}
|
||||||
|
|
||||||
- (void) addEventHandler:(NSString *) eventName
|
- (void) addEventHandler:(NSNumber *) listenerId
|
||||||
|
eventName:(NSString *) eventName
|
||||||
{
|
{
|
||||||
if (![self isListeningTo:eventName]) {
|
if (![_listeners objectForKey:listenerId]) {
|
||||||
id withBlock = ^(FIRDataSnapshot * _Nonnull snapshot) {
|
id withBlock = ^(FIRDataSnapshot * _Nonnull snapshot) {
|
||||||
NSDictionary *props = [RNFirebaseDBReference snapshotToDict:snapshot];
|
NSDictionary *props = [RNFirebaseDBReference snapshotToDict:snapshot];
|
||||||
[self sendJSEvent:DATABASE_DATA_EVENT
|
[self sendJSEvent:DATABASE_DATA_EVENT
|
||||||
title:eventName
|
title:eventName
|
||||||
props: @{
|
props: @{
|
||||||
@"eventName": eventName,
|
@"eventName": eventName,
|
||||||
|
@"refId": _refId,
|
||||||
|
@"listenerId": listenerId,
|
||||||
@"path": _path,
|
@"path": _path,
|
||||||
@"modifiersString": _modifiersString,
|
|
||||||
@"snapshot": props
|
@"snapshot": props
|
||||||
}];
|
}];
|
||||||
};
|
};
|
||||||
id errorBlock = ^(NSError * _Nonnull error) {
|
id errorBlock = ^(NSError * _Nonnull error) {
|
||||||
NSLog(@"Error onDBEvent: %@", [error debugDescription]);
|
NSLog(@"Error onDBEvent: %@", [error debugDescription]);
|
||||||
[self unsetListeningOn:eventName];
|
[self removeEventHandler:listenerId eventName:eventName];
|
||||||
[self getAndSendDatabaseError:error
|
[self getAndSendDatabaseError:error
|
||||||
path:_path
|
listenerId:listenerId];
|
||||||
modifiersString:_modifiersString];
|
|
||||||
};
|
};
|
||||||
int eventType = [self eventTypeFromName:eventName];
|
int eventType = [self eventTypeFromName:eventName];
|
||||||
FIRDatabaseHandle handle = [_query observeEventType:eventType
|
FIRDatabaseHandle handle = [_query observeEventType:eventType
|
||||||
withBlock:withBlock
|
withBlock:withBlock
|
||||||
withCancelBlock:errorBlock];
|
withCancelBlock:errorBlock];
|
||||||
[self setEventHandler:handle forName:eventName];
|
[_listeners setObject:@(handle) forKey:listenerId];
|
||||||
} else {
|
} else {
|
||||||
NSLog(@"Warning Trying to add duplicate listener for type: %@ with modifiers: %@ for path: %@", eventName, _modifiersString, _path);
|
NSLog(@"Warning Trying to add duplicate listener for refId: %@ listenerId: %@", _refId, listenerId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -74,7 +71,7 @@
|
||||||
callback(@[[NSNull null], @{
|
callback(@[[NSNull null], @{
|
||||||
@"eventName": @"value",
|
@"eventName": @"value",
|
||||||
@"path": _path,
|
@"path": _path,
|
||||||
@"modifiersString": _modifiersString,
|
@"refId": _refId,
|
||||||
@"snapshot": props
|
@"snapshot": props
|
||||||
}]);
|
}]);
|
||||||
}
|
}
|
||||||
|
@ -83,7 +80,7 @@
|
||||||
callback(@[@{
|
callback(@[@{
|
||||||
@"eventName": DATABASE_ERROR_EVENT,
|
@"eventName": DATABASE_ERROR_EVENT,
|
||||||
@"path": _path,
|
@"path": _path,
|
||||||
@"modifiers": _modifiersString,
|
@"refId": _refId,
|
||||||
@"code": @([error code]),
|
@"code": @([error code]),
|
||||||
@"details": [error debugDescription],
|
@"details": [error debugDescription],
|
||||||
@"message": [error localizedDescription],
|
@"message": [error localizedDescription],
|
||||||
|
@ -92,44 +89,14 @@
|
||||||
}];
|
}];
|
||||||
}
|
}
|
||||||
|
|
||||||
- (void) removeEventHandler:(NSString *) name
|
- (void) removeEventHandler:(NSNumber *) listenerId
|
||||||
|
eventName:(NSString *) eventName
|
||||||
{
|
{
|
||||||
int eventType = [self eventTypeFromName:name];
|
FIRDatabaseHandle handle = [[_listeners objectForKey:listenerId] integerValue];
|
||||||
switch (eventType) {
|
if (handle) {
|
||||||
case FIRDataEventTypeValue:
|
[_listeners removeObjectForKey:listenerId];
|
||||||
if (self.childValueHandler != nil) {
|
[_query removeObserverWithHandle:handle];
|
||||||
[_query removeObserverWithHandle:self.childValueHandler];
|
|
||||||
self.childValueHandler = nil;
|
|
||||||
}
|
}
|
||||||
break;
|
|
||||||
case FIRDataEventTypeChildAdded:
|
|
||||||
if (self.childAddedHandler != nil) {
|
|
||||||
[_query removeObserverWithHandle:self.childAddedHandler];
|
|
||||||
self.childAddedHandler = nil;
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case FIRDataEventTypeChildChanged:
|
|
||||||
if (self.childModifiedHandler != nil) {
|
|
||||||
[_query removeObserverWithHandle:self.childModifiedHandler];
|
|
||||||
self.childModifiedHandler = nil;
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case FIRDataEventTypeChildRemoved:
|
|
||||||
if (self.childRemovedHandler != nil) {
|
|
||||||
[_query removeObserverWithHandle:self.childRemovedHandler];
|
|
||||||
self.childRemovedHandler = nil;
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case FIRDataEventTypeChildMoved:
|
|
||||||
if (self.childMovedHandler != nil) {
|
|
||||||
[_query removeObserverWithHandle:self.childMovedHandler];
|
|
||||||
self.childMovedHandler = nil;
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
[self unsetListeningOn:name];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
+ (NSDictionary *) snapshotToDict:(FIRDataSnapshot *) snapshot
|
+ (NSDictionary *) snapshotToDict:(FIRDataSnapshot *) snapshot
|
||||||
|
@ -159,21 +126,19 @@
|
||||||
}
|
}
|
||||||
|
|
||||||
- (NSDictionary *) getAndSendDatabaseError:(NSError *) error
|
- (NSDictionary *) getAndSendDatabaseError:(NSError *) error
|
||||||
path:(NSString *) path
|
listenerId:(NSNumber *) listenerId
|
||||||
modifiersString:(NSString *) modifiersString
|
|
||||||
{
|
{
|
||||||
NSDictionary *event = @{
|
NSDictionary *event = @{
|
||||||
@"eventName": DATABASE_ERROR_EVENT,
|
@"eventName": DATABASE_ERROR_EVENT,
|
||||||
@"path": path,
|
@"path": _path,
|
||||||
@"modifiers": modifiersString,
|
@"refId": _refId,
|
||||||
|
@"listenerId": listenerId,
|
||||||
@"code": @([error code]),
|
@"code": @([error code]),
|
||||||
@"details": [error debugDescription],
|
@"details": [error debugDescription],
|
||||||
@"message": [error localizedDescription],
|
@"message": [error localizedDescription],
|
||||||
@"description": [error description]
|
@"description": [error description]
|
||||||
};
|
};
|
||||||
|
|
||||||
// [self sendJSEvent:DATABASE_ERROR_EVENT title:DATABASE_ERROR_EVENT props: event];
|
|
||||||
|
|
||||||
@try {
|
@try {
|
||||||
[_emitter sendEventWithName:DATABASE_ERROR_EVENT body:event];
|
[_emitter sendEventWithName:DATABASE_ERROR_EVENT body:event];
|
||||||
}
|
}
|
||||||
|
@ -194,69 +159,58 @@
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
- (FIRDatabaseQuery *) buildQueryAtPathWithModifiers:(FIRDatabase*) database
|
- (FIRDatabaseQuery *) buildQueryAtPathWithModifiers:(FIRDatabase*) database
|
||||||
path:(NSString*) path
|
path:(NSString*) path
|
||||||
modifiers:(NSArray *) modifiers
|
modifiers:(NSArray *) modifiers
|
||||||
{
|
{
|
||||||
FIRDatabaseQuery *query = [[database reference] child:path];
|
FIRDatabaseQuery *query = [[database reference] child:path];
|
||||||
|
|
||||||
for (NSString *str in modifiers) {
|
for (NSDictionary *modifier in modifiers) {
|
||||||
if ([str isEqualToString:@"orderByKey"]) {
|
NSString *type = [modifier valueForKey:@"type"];
|
||||||
|
NSString *name = [modifier valueForKey:@"name"];
|
||||||
|
if ([type isEqualToString:@"orderBy"]) {
|
||||||
|
if ([name isEqualToString:@"orderByKey"]) {
|
||||||
query = [query queryOrderedByKey];
|
query = [query queryOrderedByKey];
|
||||||
} else if ([str isEqualToString:@"orderByPriority"]) {
|
} else if ([name isEqualToString:@"orderByPriority"]) {
|
||||||
query = [query queryOrderedByPriority];
|
query = [query queryOrderedByPriority];
|
||||||
} else if ([str isEqualToString:@"orderByValue"]) {
|
} else if ([name isEqualToString:@"orderByValue"]) {
|
||||||
query = [query queryOrderedByValue];
|
query = [query queryOrderedByValue];
|
||||||
} else if ([str containsString:@"orderByChild"]) {
|
} else if ([name isEqualToString:@"orderByChild"]) {
|
||||||
NSArray *args = [str componentsSeparatedByString:@":"];
|
NSString *key = [modifier valueForKey:@"key"];
|
||||||
NSString *key = args[1];
|
|
||||||
query = [query queryOrderedByChild:key];
|
query = [query queryOrderedByChild:key];
|
||||||
} else if ([str containsString:@"limitToLast"]) {
|
}
|
||||||
NSArray *args = [str componentsSeparatedByString:@":"];
|
} else if ([type isEqualToString:@"limit"]) {
|
||||||
NSString *key = args[1];
|
int limit = [[modifier valueForKey:@"limit"] integerValue];
|
||||||
NSUInteger limit = key.integerValue;
|
if ([name isEqualToString:@"limitToLast"]) {
|
||||||
query = [query queryLimitedToLast:limit];
|
query = [query queryLimitedToLast:limit];
|
||||||
} else if ([str containsString:@"limitToFirst"]) {
|
} else if ([name isEqualToString:@"limitToFirst"]) {
|
||||||
NSArray *args = [str componentsSeparatedByString:@":"];
|
|
||||||
NSString *key = args[1];
|
|
||||||
NSUInteger limit = key.integerValue;
|
|
||||||
query = [query queryLimitedToFirst:limit];
|
query = [query queryLimitedToFirst:limit];
|
||||||
} else if ([str containsString:@"equalTo"]) {
|
}
|
||||||
NSArray *args = [str componentsSeparatedByString:@":"];
|
} else if ([type isEqualToString:@"filter"]) {
|
||||||
int size = (int)[args count];;
|
NSString* valueType = [modifier valueForKey:@"valueType"];
|
||||||
id value = [self getIdValue:args[1] type:args[2]];
|
NSString* key = [modifier valueForKey:@"key"];
|
||||||
if (size > 3) {
|
id value = [self getIdValue:[modifier valueForKey:@"value"] type:valueType];
|
||||||
NSString *key = args[3];
|
if ([name isEqualToString:@"equalTo"]) {
|
||||||
query = [query queryEqualToValue:value
|
if (key != nil) {
|
||||||
childKey:key];
|
query = [query queryEqualToValue:value childKey:key];
|
||||||
} else {
|
} else {
|
||||||
query = [query queryEqualToValue:value];
|
query = [query queryEqualToValue:value];
|
||||||
}
|
}
|
||||||
} else if ([str containsString:@"endAt"]) {
|
} else if ([name isEqualToString:@"endAt"]) {
|
||||||
NSArray *args = [str componentsSeparatedByString:@":"];
|
if (key != nil) {
|
||||||
int size = (int)[args count];;
|
query = [query queryEndingAtValue:value childKey:key];
|
||||||
id value = [self getIdValue:args[1] type:args[2]];
|
|
||||||
if (size > 3) {
|
|
||||||
NSString *key = args[3];
|
|
||||||
query = [query queryEndingAtValue:value
|
|
||||||
childKey:key];
|
|
||||||
} else {
|
} else {
|
||||||
query = [query queryEndingAtValue:value];
|
query = [query queryEndingAtValue:value];
|
||||||
}
|
}
|
||||||
} else if ([str containsString:@"startAt"]) {
|
} else if ([name isEqualToString:@"startAt"]) {
|
||||||
NSArray *args = [str componentsSeparatedByString:@":"];
|
if (key != nil) {
|
||||||
id value = [self getIdValue:args[1] type:args[2]];
|
query = [query queryStartingAtValue:value childKey:key];
|
||||||
int size = (int)[args count];;
|
|
||||||
if (size > 3) {
|
|
||||||
NSString *key = args[3];
|
|
||||||
query = [query queryStartingAtValue:value
|
|
||||||
childKey:key];
|
|
||||||
} else {
|
} else {
|
||||||
query = [query queryStartingAtValue:value];
|
query = [query queryStartingAtValue:value];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return query;
|
return query;
|
||||||
}
|
}
|
||||||
|
@ -273,58 +227,11 @@
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
- (void) setEventHandler:(FIRDatabaseHandle) handle
|
|
||||||
forName:(NSString *) name
|
|
||||||
{
|
|
||||||
int eventType = [self eventTypeFromName:name];
|
|
||||||
switch (eventType) {
|
|
||||||
case FIRDataEventTypeValue:
|
|
||||||
self.childValueHandler = handle;
|
|
||||||
break;
|
|
||||||
case FIRDataEventTypeChildAdded:
|
|
||||||
self.childAddedHandler = handle;
|
|
||||||
break;
|
|
||||||
case FIRDataEventTypeChildChanged:
|
|
||||||
self.childModifiedHandler = handle;
|
|
||||||
break;
|
|
||||||
case FIRDataEventTypeChildRemoved:
|
|
||||||
self.childRemovedHandler = handle;
|
|
||||||
break;
|
|
||||||
case FIRDataEventTypeChildMoved:
|
|
||||||
self.childMovedHandler = handle;
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
[self setListeningOn:name withHandle:handle];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void) setListeningOn:(NSString *) name
|
|
||||||
withHandle:(FIRDatabaseHandle) handle
|
|
||||||
{
|
|
||||||
[_listeners setValue:@(handle) forKey:name];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void) unsetListeningOn:(NSString *) name
|
|
||||||
{
|
|
||||||
[_listeners removeObjectForKey:name];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (BOOL) isListeningTo:(NSString *) name
|
|
||||||
{
|
|
||||||
return [_listeners valueForKey:name] != nil;
|
|
||||||
}
|
|
||||||
|
|
||||||
- (BOOL) hasListeners
|
- (BOOL) hasListeners
|
||||||
{
|
{
|
||||||
return [[_listeners allKeys] count] > 0;
|
return [[_listeners allKeys] count] > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
- (NSArray *) listenerKeys
|
|
||||||
{
|
|
||||||
return [_listeners allKeys];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (int) eventTypeFromName:(NSString *)name
|
- (int) eventTypeFromName:(NSString *)name
|
||||||
{
|
{
|
||||||
int eventType = FIRDataEventTypeValue;
|
int eventType = FIRDataEventTypeValue;
|
||||||
|
@ -343,24 +250,6 @@
|
||||||
return eventType;
|
return eventType;
|
||||||
}
|
}
|
||||||
|
|
||||||
- (void) cleanup {
|
|
||||||
if (self.childValueHandler > 0) {
|
|
||||||
[self removeEventHandler:DATABASE_VALUE_EVENT];
|
|
||||||
}
|
|
||||||
if (self.childAddedHandler > 0) {
|
|
||||||
[self removeEventHandler:DATABASE_CHILD_ADDED_EVENT];
|
|
||||||
}
|
|
||||||
if (self.childModifiedHandler > 0) {
|
|
||||||
[self removeEventHandler:DATABASE_CHILD_MODIFIED_EVENT];
|
|
||||||
}
|
|
||||||
if (self.childRemovedHandler > 0) {
|
|
||||||
[self removeEventHandler:DATABASE_CHILD_REMOVED_EVENT];
|
|
||||||
}
|
|
||||||
if (self.childMovedHandler > 0) {
|
|
||||||
[self removeEventHandler:DATABASE_CHILD_MOVED_EVENT];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
@end
|
||||||
|
|
||||||
|
|
||||||
|
@ -558,58 +447,50 @@ RCT_EXPORT_METHOD(push:(NSString *) path
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
RCT_EXPORT_METHOD(on:(nonnull NSNumber *) refId
|
||||||
RCT_EXPORT_METHOD(on:(NSString *) path
|
path:(NSString *) path
|
||||||
modifiersString:(NSString *) modifiersString
|
|
||||||
modifiers:(NSArray *) modifiers
|
modifiers:(NSArray *) modifiers
|
||||||
|
listenerId:(nonnull NSNumber *) listenerId
|
||||||
name:(NSString *) eventName
|
name:(NSString *) eventName
|
||||||
callback:(RCTResponseSenderBlock) callback)
|
callback:(RCTResponseSenderBlock) callback)
|
||||||
{
|
{
|
||||||
RNFirebaseDBReference *ref = [self getDBHandle:path modifiers:modifiers modifiersString:modifiersString];
|
RNFirebaseDBReference *ref = [self getDBHandle:refId path:path modifiers:modifiers];
|
||||||
[ref addEventHandler:eventName];
|
[ref addEventHandler:listenerId eventName:eventName];
|
||||||
callback(@[[NSNull null], @{
|
callback(@[[NSNull null], @{
|
||||||
@"status": @"success",
|
@"status": @"success",
|
||||||
|
@"refId": refId,
|
||||||
@"handle": path
|
@"handle": path
|
||||||
}]);
|
}]);
|
||||||
}
|
}
|
||||||
|
|
||||||
RCT_EXPORT_METHOD(once:(NSString *) path
|
RCT_EXPORT_METHOD(once:(nonnull NSNumber *) refId
|
||||||
modifiersString:(NSString *) modifiersString
|
path:(NSString *) path
|
||||||
modifiers:(NSArray *) modifiers
|
modifiers:(NSArray *) modifiers
|
||||||
name:(NSString *) name
|
|
||||||
callback:(RCTResponseSenderBlock) callback)
|
|
||||||
{
|
|
||||||
RNFirebaseDBReference *ref = [self getDBHandle:path modifiers:modifiers modifiersString:modifiersString];
|
|
||||||
[ref addSingleEventHandler:callback];
|
|
||||||
}
|
|
||||||
|
|
||||||
RCT_EXPORT_METHOD(off:(NSString *)path
|
|
||||||
modifiersString:(NSString *) modifiersString
|
|
||||||
eventName:(NSString *) eventName
|
eventName:(NSString *) eventName
|
||||||
callback:(RCTResponseSenderBlock) callback)
|
callback:(RCTResponseSenderBlock) callback)
|
||||||
{
|
{
|
||||||
NSString *key = [self getDBListenerKey:path withModifiers:modifiersString];
|
RNFirebaseDBReference *ref = [self getDBHandle:refId path:path modifiers:modifiers];
|
||||||
NSArray *listenerKeys;
|
[ref addSingleEventHandler:callback];
|
||||||
RNFirebaseDBReference *ref = [_dbReferences objectForKey:key];
|
}
|
||||||
if (ref == nil) {
|
|
||||||
listenerKeys = @[];
|
RCT_EXPORT_METHOD(off:(nonnull NSNumber *) refId
|
||||||
} else {
|
listeners:(NSArray *) listeners
|
||||||
if (eventName == nil || [eventName isEqualToString:@""]) {
|
callback:(RCTResponseSenderBlock) callback)
|
||||||
[ref cleanup];
|
{
|
||||||
[_dbReferences removeObjectForKey:key];
|
RNFirebaseDBReference *ref = [_dbReferences objectForKey:refId];
|
||||||
} else {
|
if (ref != nil) {
|
||||||
[ref removeEventHandler:eventName];
|
for (NSDictionary *listener in listeners) {
|
||||||
|
NSNumber *listenerId = [listener valueForKey:@"listenerId"];
|
||||||
|
NSString *eventName = [listener valueForKey:@"eventName"];
|
||||||
|
[ref removeEventHandler:listenerId eventName:eventName];
|
||||||
if (![ref hasListeners]) {
|
if (![ref hasListeners]) {
|
||||||
[_dbReferences removeObjectForKey:key];
|
[_dbReferences removeObjectForKey:refId];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
listenerKeys = [ref listenerKeys];
|
|
||||||
}
|
}
|
||||||
callback(@[[NSNull null], @{
|
callback(@[[NSNull null], @{
|
||||||
@"result": @"success",
|
@"status": @"success",
|
||||||
@"handle": path,
|
@"refId": refId,
|
||||||
@"modifiersString": modifiersString,
|
|
||||||
@"remainingListeners": listenerKeys,
|
|
||||||
}]);
|
}]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -680,30 +561,23 @@ RCT_EXPORT_METHOD(goOnline)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
- (RNFirebaseDBReference *) getDBHandle:(NSString *) path
|
- (RNFirebaseDBReference *) getDBHandle:(NSNumber *) refId
|
||||||
modifiers:modifiers
|
path:(NSString *) path
|
||||||
modifiersString:modifiersString
|
modifiers:(NSArray *) modifiers
|
||||||
{
|
{
|
||||||
NSString *key = [self getDBListenerKey:path withModifiers:modifiersString];
|
RNFirebaseDBReference *ref = [_dbReferences objectForKey:refId];
|
||||||
RNFirebaseDBReference *ref = [_dbReferences objectForKey:key];
|
|
||||||
|
|
||||||
if (ref == nil) {
|
if (ref == nil) {
|
||||||
ref = [[RNFirebaseDBReference alloc] initWithPathAndModifiers:self
|
ref = [[RNFirebaseDBReference alloc] initWithPathAndModifiers:self
|
||||||
database:[FIRDatabase database]
|
database:[FIRDatabase database]
|
||||||
|
refId:refId
|
||||||
path:path
|
path:path
|
||||||
modifiers:modifiers
|
modifiers:modifiers];
|
||||||
modifiersString:modifiersString];
|
[_dbReferences setObject:ref forKey:refId];
|
||||||
[_dbReferences setObject:ref forKey:key];
|
|
||||||
}
|
}
|
||||||
return ref;
|
return ref;
|
||||||
}
|
}
|
||||||
|
|
||||||
- (NSString *) getDBListenerKey:(NSString *) path
|
|
||||||
withModifiers:(NSString *) modifiersString
|
|
||||||
{
|
|
||||||
return [NSString stringWithFormat:@"%@ | %@", path, modifiersString, nil];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Not sure how to get away from this... yet
|
// Not sure how to get away from this... yet
|
||||||
- (NSArray<NSString *> *)supportedEvents {
|
- (NSArray<NSString *> *)supportedEvents {
|
||||||
return @[DATABASE_DATA_EVENT, DATABASE_ERROR_EVENT, DATABASE_TRANSACTION_EVENT];
|
return @[DATABASE_DATA_EVENT, DATABASE_ERROR_EVENT, DATABASE_TRANSACTION_EVENT];
|
||||||
|
|
16
lib/flow.js
16
lib/flow.js
|
@ -15,6 +15,22 @@ declare type CredentialType = {
|
||||||
secret: string
|
secret: string
|
||||||
};
|
};
|
||||||
|
|
||||||
|
declare type DatabaseListener = {
|
||||||
|
listenerId: number;
|
||||||
|
eventName: string;
|
||||||
|
successCallback: Function;
|
||||||
|
failureCallback?: Function;
|
||||||
|
};
|
||||||
|
|
||||||
|
declare type DatabaseModifier = {
|
||||||
|
type: 'orderBy' | 'limit' | 'filter';
|
||||||
|
name?: string;
|
||||||
|
key?: string;
|
||||||
|
limit?: number;
|
||||||
|
value?: any;
|
||||||
|
valueType?: string;
|
||||||
|
};
|
||||||
|
|
||||||
declare type GoogleApiAvailabilityType = {
|
declare type GoogleApiAvailabilityType = {
|
||||||
status: number,
|
status: number,
|
||||||
isAvailable: boolean,
|
isAvailable: boolean,
|
||||||
|
|
|
@ -19,9 +19,8 @@ const FirebaseDatabaseEvt = new NativeEventEmitter(FirebaseDatabase);
|
||||||
export default class Database extends Base {
|
export default class Database extends Base {
|
||||||
constructor(firebase: Object, options: Object = {}) {
|
constructor(firebase: Object, options: Object = {}) {
|
||||||
super(firebase, options);
|
super(firebase, options);
|
||||||
this.subscriptions = {};
|
this.references = {};
|
||||||
this.serverTimeOffset = 0;
|
this.serverTimeOffset = 0;
|
||||||
this.errorSubscriptions = {};
|
|
||||||
this.persistenceEnabled = false;
|
this.persistenceEnabled = false;
|
||||||
this.namespace = 'firebase:database';
|
this.namespace = 'firebase:database';
|
||||||
this.transaction = new TransactionHandler(firebase, this, FirebaseDatabaseEvt);
|
this.transaction = new TransactionHandler(firebase, this, FirebaseDatabaseEvt);
|
||||||
|
@ -68,20 +67,12 @@ export default class Database extends Base {
|
||||||
* @param errorCb
|
* @param errorCb
|
||||||
* @returns {*}
|
* @returns {*}
|
||||||
*/
|
*/
|
||||||
on(path: string, modifiersString: string, modifiers: Array<string>, eventName: string, cb: () => void, errorCb: () => void) {
|
on(ref: Reference, listener: DatabaseListener) {
|
||||||
const handle = this._handle(path, modifiersString);
|
const { refId, path, query } = ref;
|
||||||
this.log.debug('adding on listener', handle);
|
const { listenerId, eventName } = listener;
|
||||||
|
this.log.debug('on() : ', ref.refId, listenerId, eventName);
|
||||||
if (!this.subscriptions[handle]) this.subscriptions[handle] = {};
|
this.references[refId] = ref;
|
||||||
if (!this.subscriptions[handle][eventName]) this.subscriptions[handle][eventName] = [];
|
return promisify('on', FirebaseDatabase)(refId, path, query.getModifiers(), listenerId, eventName);
|
||||||
this.subscriptions[handle][eventName].push(cb);
|
|
||||||
|
|
||||||
if (errorCb) {
|
|
||||||
if (!this.errorSubscriptions[handle]) this.errorSubscriptions[handle] = [];
|
|
||||||
this.errorSubscriptions[handle].push(errorCb);
|
|
||||||
}
|
|
||||||
|
|
||||||
return promisify('on', FirebaseDatabase)(path, modifiersString, modifiers, eventName);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -92,49 +83,35 @@ export default class Database extends Base {
|
||||||
* @param origCB
|
* @param origCB
|
||||||
* @returns {*}
|
* @returns {*}
|
||||||
*/
|
*/
|
||||||
off(path: string, modifiersString: string, eventName?: string, origCB?: () => void) {
|
off(
|
||||||
const handle = this._handle(path, modifiersString);
|
refId: number,
|
||||||
this.log.debug('off() : ', handle, eventName);
|
// $FlowFixMe
|
||||||
|
listeners: Array<DatabaseListener>,
|
||||||
|
remainingListenersCount: number
|
||||||
|
) {
|
||||||
|
this.log.debug('off() : ', refId, listeners);
|
||||||
|
|
||||||
if (!this.subscriptions[handle] || (eventName && !this.subscriptions[handle][eventName])) {
|
// Delete the reference if there are no more listeners
|
||||||
this.log.warn('off() called, but not currently listening at that location (bad path)', handle, eventName);
|
if (remainingListenersCount === 0) delete this.references[refId];
|
||||||
return Promise.resolve();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (eventName && origCB) {
|
if (listeners.length === 0) return Promise.resolve();
|
||||||
const i = this.subscriptions[handle][eventName].indexOf(origCB);
|
|
||||||
|
|
||||||
if (i === -1) {
|
return promisify('off', FirebaseDatabase)(refId, listeners.map(listener => ({
|
||||||
this.log.warn('off() called, but the callback specified is not listening at that location (bad path)', handle, eventName);
|
listenerId: listener.listenerId,
|
||||||
return Promise.resolve();
|
eventName: listener.eventName,
|
||||||
}
|
})));
|
||||||
|
|
||||||
this.subscriptions[handle][eventName].splice(i, 1);
|
|
||||||
if (this.subscriptions[handle][eventName].length > 0) return Promise.resolve();
|
|
||||||
} else if (eventName) {
|
|
||||||
this.subscriptions[handle][eventName] = [];
|
|
||||||
} else {
|
|
||||||
this.subscriptions[handle] = {};
|
|
||||||
}
|
|
||||||
this.errorSubscriptions[handle] = [];
|
|
||||||
return promisify('off', FirebaseDatabase)(path, modifiersString, eventName);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Removes all event handlers and their native subscriptions
|
* Removes all references and their native listeners
|
||||||
* @returns {Promise.<*>}
|
* @returns {Promise.<*>}
|
||||||
*/
|
*/
|
||||||
cleanup() {
|
cleanup() {
|
||||||
const promises = [];
|
const promises = [];
|
||||||
Object.keys(this.subscriptions).forEach((handle) => {
|
Object.keys(this.references).forEach((refId) => {
|
||||||
Object.keys(this.subscriptions[handle]).forEach((eventName) => {
|
const ref = this.references[refId];
|
||||||
const separator = handle.indexOf('|');
|
promises.push(this.off(Number(refId), Object.values(ref.listeners), 0));
|
||||||
const path = handle.substring(0, separator);
|
|
||||||
const modifiersString = handle.substring(separator + 1);
|
|
||||||
promises.push(this.off(path, modifiersString, eventName));
|
|
||||||
});
|
});
|
||||||
});
|
|
||||||
|
|
||||||
return Promise.all(promises);
|
return Promise.all(promises);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -169,18 +146,6 @@ export default class Database extends Base {
|
||||||
return Promise.reject({ status: 'Already enabled' });
|
return Promise.reject({ status: 'Already enabled' });
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
*
|
|
||||||
* @param path
|
|
||||||
* @param modifiersString
|
|
||||||
* @returns {string}
|
|
||||||
* @private
|
|
||||||
*/
|
|
||||||
_handle(path: string = '', modifiersString: string = '') {
|
|
||||||
return `${path}|${modifiersString}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* @param event
|
* @param event
|
||||||
|
@ -188,18 +153,14 @@ export default class Database extends Base {
|
||||||
*/
|
*/
|
||||||
_handleDatabaseEvent(event: Object) {
|
_handleDatabaseEvent(event: Object) {
|
||||||
const body = event.body || {};
|
const body = event.body || {};
|
||||||
const { path, modifiersString, eventName, snapshot } = body;
|
const { refId, listenerId, path, eventName, snapshot } = body;
|
||||||
const handle = this._handle(path, modifiersString);
|
this.log.debug('_handleDatabaseEvent: ', refId, listenerId, path, eventName, snapshot && snapshot.key);
|
||||||
|
if (this.references[refId] && this.references[refId].listeners[listenerId]) {
|
||||||
this.log.debug('_handleDatabaseEvent: ', handle, eventName, snapshot && snapshot.key);
|
const cb = this.references[refId].listeners[listenerId].successCallback;
|
||||||
|
cb(new Snapshot(this.references[refId], snapshot));
|
||||||
if (this.subscriptions[handle] && this.subscriptions[handle][eventName]) {
|
|
||||||
this.subscriptions[handle][eventName].forEach((cb) => {
|
|
||||||
cb(new Snapshot(new Reference(this, path, modifiersString.split('|')), snapshot), body);
|
|
||||||
});
|
|
||||||
} else {
|
} else {
|
||||||
FirebaseDatabase.off(path, modifiersString, eventName, () => {
|
FirebaseDatabase.off(refId, [{ listenerId, eventName }], () => {
|
||||||
this.log.debug('_handleDatabaseEvent: No JS listener registered, removed native listener', handle, eventName);
|
this.log.debug('_handleDatabaseEvent: No JS listener registered, removed native listener', refId, listenerId, eventName);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -235,13 +196,15 @@ export default class Database extends Base {
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
_handleDatabaseError(error: Object = {}) {
|
_handleDatabaseError(error: Object = {}) {
|
||||||
const { path, modifiers } = error;
|
const { refId, listenerId, path } = error;
|
||||||
const handle = this._handle(path, modifiers);
|
|
||||||
const firebaseError = this._toFirebaseError(error);
|
const firebaseError = this._toFirebaseError(error);
|
||||||
|
|
||||||
this.log.debug('_handleDatabaseError ->', handle, 'database_error', error);
|
this.log.debug('_handleDatabaseError ->', refId, listenerId, path, 'database_error', error);
|
||||||
|
|
||||||
if (this.errorSubscriptions[handle]) this.errorSubscriptions[handle].forEach(listener => listener(firebaseError));
|
if (this.references[refId] && this.references[refId].listeners[listenerId]) {
|
||||||
|
const failureCb = this.references[refId].listeners[listenerId].failureCallback;
|
||||||
|
if (failureCb) failureCb(firebaseError);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -250,4 +213,3 @@ export const statics = {
|
||||||
TIMESTAMP: FirebaseDatabase.serverValueTimestamp || { '.sv': 'timestamp' },
|
TIMESTAMP: FirebaseDatabase.serverValueTimestamp || { '.sv': 'timestamp' },
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
@ -9,47 +9,41 @@ import Reference from './reference.js';
|
||||||
* @class Query
|
* @class Query
|
||||||
*/
|
*/
|
||||||
export default class Query extends ReferenceBase {
|
export default class Query extends ReferenceBase {
|
||||||
static ref: Reference;
|
modifiers: Array<DatabaseModifier>;
|
||||||
|
|
||||||
static modifiers: Array<string>;
|
constructor(ref: Reference, path: string, existingModifiers?: Array<DatabaseModifier>) {
|
||||||
|
|
||||||
ref: Reference;
|
|
||||||
|
|
||||||
constructor(ref: Reference, path: string, existingModifiers?: Array<string>) {
|
|
||||||
super(ref.database, path);
|
super(ref.database, path);
|
||||||
this.log.debug('creating Query ', path, existingModifiers);
|
this.log.debug('creating Query ', path, existingModifiers);
|
||||||
this.ref = ref;
|
|
||||||
this.modifiers = existingModifiers ? [...existingModifiers] : [];
|
this.modifiers = existingModifiers ? [...existingModifiers] : [];
|
||||||
}
|
}
|
||||||
|
|
||||||
setOrderBy(name: string, key?: string) {
|
orderBy(name: string, key?: string) {
|
||||||
if (key) {
|
this.modifiers.push({
|
||||||
this.modifiers.push(`${name}:${key}`);
|
type: 'orderBy',
|
||||||
} else {
|
name,
|
||||||
this.modifiers.push(name);
|
key,
|
||||||
}
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
setLimit(name: string, limit: number) {
|
limit(name: string, limit: number) {
|
||||||
this.modifiers.push(`${name}:${limit}`);
|
this.modifiers.push({
|
||||||
|
type: 'limit',
|
||||||
|
name,
|
||||||
|
limit,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
setFilter(name: string, value: any, key?:string) {
|
filter(name: string, value: any, key?:string) {
|
||||||
if (key) {
|
this.modifiers.push({
|
||||||
this.modifiers.push(`${name}:${value}:${typeof value}:${key}`);
|
type: 'filter',
|
||||||
} else {
|
name,
|
||||||
this.modifiers.push(`${name}:${value}:${typeof value}`);
|
value,
|
||||||
}
|
valueType: typeof value,
|
||||||
|
key,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
getModifiers(): Array<string> {
|
getModifiers(): Array<DatabaseModifier> {
|
||||||
return [...this.modifiers];
|
return [...this.modifiers];
|
||||||
}
|
}
|
||||||
|
|
||||||
getModifiersString(): string {
|
|
||||||
if (!this.modifiers || !Array.isArray(this.modifiers)) {
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
return this.modifiers.join('|');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,6 +10,8 @@ import { ReferenceBase } from './../base';
|
||||||
import { promisify, isFunction, isObject, tryJSONParse, tryJSONStringify, generatePushID } from './../../utils';
|
import { promisify, isFunction, isObject, tryJSONParse, tryJSONStringify, generatePushID } from './../../utils';
|
||||||
|
|
||||||
const FirebaseDatabase = NativeModules.RNFirebaseDatabase;
|
const FirebaseDatabase = NativeModules.RNFirebaseDatabase;
|
||||||
|
// Unique Reference ID for native events
|
||||||
|
let refId = 1;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @link https://firebase.google.com/docs/reference/js/firebase.database.Reference
|
* @link https://firebase.google.com/docs/reference/js/firebase.database.Reference
|
||||||
|
@ -17,15 +19,19 @@ const FirebaseDatabase = NativeModules.RNFirebaseDatabase;
|
||||||
*/
|
*/
|
||||||
export default class Reference extends ReferenceBase {
|
export default class Reference extends ReferenceBase {
|
||||||
|
|
||||||
|
refId: number;
|
||||||
|
listeners: { [listenerId: number]: DatabaseListener };
|
||||||
database: FirebaseDatabase;
|
database: FirebaseDatabase;
|
||||||
query: Query;
|
query: Query;
|
||||||
|
|
||||||
constructor(database: FirebaseDatabase, path: string, existingModifiers?: Array<string>) {
|
constructor(database: FirebaseDatabase, path: string, existingModifiers?: Array<DatabaseModifier>) {
|
||||||
super(database.firebase, path);
|
super(database.firebase, path);
|
||||||
|
this.refId = refId++;
|
||||||
|
this.listeners = {};
|
||||||
this.database = database;
|
this.database = database;
|
||||||
this.namespace = 'firebase:db:ref';
|
this.namespace = 'firebase:db:ref';
|
||||||
this.query = new Query(this, path, existingModifiers);
|
this.query = new Query(this, path, existingModifiers);
|
||||||
this.log.debug('Created new Reference', this.database._handle(path, existingModifiers));
|
this.log.debug('Created new Reference', this.refId, this.path);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -81,7 +87,6 @@ export default class Reference extends ReferenceBase {
|
||||||
|
|
||||||
const path = this.path;
|
const path = this.path;
|
||||||
const _value = this._serializeAnyType(value);
|
const _value = this._serializeAnyType(value);
|
||||||
|
|
||||||
return promisify('push', FirebaseDatabase)(path, _value)
|
return promisify('push', FirebaseDatabase)(path, _value)
|
||||||
.then(({ ref }) => {
|
.then(({ ref }) => {
|
||||||
const newRef = new Reference(this.database, ref);
|
const newRef = new Reference(this.database, ref);
|
||||||
|
@ -95,36 +100,37 @@ export default class Reference extends ReferenceBase {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* @param eventType
|
* @param eventName
|
||||||
* @param successCallback
|
* @param successCallback
|
||||||
* @param failureCallback
|
* @param failureCallback
|
||||||
* @param context TODO
|
* @param context TODO
|
||||||
* @returns {*}
|
* @returns {*}
|
||||||
*/
|
*/
|
||||||
on(eventType: string, successCallback: () => any, failureCallback: () => any) {
|
on(eventName: string, successCallback: () => any, failureCallback: () => any) {
|
||||||
if (!isFunction(successCallback)) throw new Error('The specified callback must be a function');
|
if (!isFunction(successCallback)) throw new Error('The specified callback must be a function');
|
||||||
if (failureCallback && !isFunction(failureCallback)) throw new Error('The specified error callback must be a function');
|
if (failureCallback && !isFunction(failureCallback)) throw new Error('The specified error callback must be a function');
|
||||||
const path = this.path;
|
this.log.debug('adding reference.on', this.refId, eventName);
|
||||||
const modifiers = this.query.getModifiers();
|
const listener = {
|
||||||
const modifiersString = this.query.getModifiersString();
|
listenerId: Object.keys(this.listeners).length + 1,
|
||||||
this.log.debug('adding reference.on', path, modifiersString, eventType);
|
eventName,
|
||||||
this.database.on(path, modifiersString, modifiers, eventType, successCallback, failureCallback);
|
successCallback,
|
||||||
|
failureCallback,
|
||||||
|
};
|
||||||
|
this.listeners[listener.listenerId] = listener;
|
||||||
|
this.database.on(this, listener);
|
||||||
return successCallback;
|
return successCallback;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* @param eventType
|
* @param eventName
|
||||||
* @param successCallback
|
* @param successCallback
|
||||||
* @param failureCallback
|
* @param failureCallback
|
||||||
* @param context TODO
|
* @param context TODO
|
||||||
* @returns {Promise.<TResult>}
|
* @returns {Promise.<TResult>}
|
||||||
*/
|
*/
|
||||||
once(eventType: string = 'value', successCallback: (snapshot: Object) => void, failureCallback: (error: Error) => void) {
|
once(eventName: string = 'value', successCallback: (snapshot: Object) => void, failureCallback: (error: FirebaseError) => void) {
|
||||||
const path = this.path;
|
return promisify('once', FirebaseDatabase)(this.refId, this.path, this.query.getModifiers(), eventName)
|
||||||
const modifiers = this.query.getModifiers();
|
|
||||||
const modifiersString = this.query.getModifiersString();
|
|
||||||
return promisify('once', FirebaseDatabase)(path, modifiersString, modifiers, eventType)
|
|
||||||
.then(({ snapshot }) => new Snapshot(this, snapshot))
|
.then(({ snapshot }) => new Snapshot(this, snapshot))
|
||||||
.then((snapshot) => {
|
.then((snapshot) => {
|
||||||
if (isFunction(successCallback)) successCallback(snapshot);
|
if (isFunction(successCallback)) successCallback(snapshot);
|
||||||
|
@ -139,15 +145,37 @@ export default class Reference extends ReferenceBase {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* @param eventType
|
* @param eventName
|
||||||
* @param origCB
|
* @param origCB
|
||||||
* @returns {*}
|
* @returns {*}
|
||||||
*/
|
*/
|
||||||
off(eventType?: string = '', origCB?: () => any) {
|
off(eventName?: string = '', origCB?: () => any) {
|
||||||
const path = this.path;
|
this.log.debug('ref.off(): ', this.refId, eventName);
|
||||||
const modifiersString = this.query.getModifiersString();
|
// $FlowFixMe
|
||||||
this.log.debug('ref.off(): ', path, modifiersString, eventType);
|
const listeners: Array<DatabaseListener> = Object.values(this.listeners);
|
||||||
return this.database.off(path, modifiersString, eventType, origCB);
|
let listenersToRemove;
|
||||||
|
if (eventName && origCB) {
|
||||||
|
listenersToRemove = listeners.filter((listener) => {
|
||||||
|
return listener.eventName === eventName && listener.successCallback === origCB;
|
||||||
|
});
|
||||||
|
// Only remove a single listener as per the web spec
|
||||||
|
if (listenersToRemove.length > 1) listenersToRemove = [listenersToRemove[0]];
|
||||||
|
} else if (eventName) {
|
||||||
|
listenersToRemove = listeners.filter((listener) => {
|
||||||
|
return listener.eventName === eventName;
|
||||||
|
});
|
||||||
|
} else if (origCB) {
|
||||||
|
listenersToRemove = listeners.filter((listener) => {
|
||||||
|
return listener.successCallback === origCB;
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
listenersToRemove = listeners;
|
||||||
|
}
|
||||||
|
// Remove the listeners from the reference to prevent memory leaks
|
||||||
|
listenersToRemove.forEach((listener) => {
|
||||||
|
delete this.listeners[listener.listenerId];
|
||||||
|
});
|
||||||
|
return this.database.off(this.refId, listenersToRemove, Object.keys(this.listeners).length);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -157,7 +185,7 @@ export default class Reference extends ReferenceBase {
|
||||||
* @param onComplete
|
* @param onComplete
|
||||||
* @param applyLocally
|
* @param applyLocally
|
||||||
*/
|
*/
|
||||||
transaction(transactionUpdate: Function, onComplete, applyLocally: boolean = false) {
|
transaction(transactionUpdate: Function, onComplete: (?Error, boolean, ?Snapshot) => *, applyLocally: boolean = false) {
|
||||||
if (!isFunction(transactionUpdate)) return Promise.reject(new Error('Missing transactionUpdate function argument.'));
|
if (!isFunction(transactionUpdate)) return Promise.reject(new Error('Missing transactionUpdate function argument.'));
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
|
@ -227,7 +255,7 @@ export default class Reference extends ReferenceBase {
|
||||||
*/
|
*/
|
||||||
orderBy(name: string, key?: string): Reference {
|
orderBy(name: string, key?: string): Reference {
|
||||||
const newRef = new Reference(this.database, this.path, this.query.getModifiers());
|
const newRef = new Reference(this.database, this.path, this.query.getModifiers());
|
||||||
newRef.query.setOrderBy(name, key);
|
newRef.query.orderBy(name, key);
|
||||||
return newRef;
|
return newRef;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -261,7 +289,7 @@ export default class Reference extends ReferenceBase {
|
||||||
*/
|
*/
|
||||||
limit(name: string, limit: number): Reference {
|
limit(name: string, limit: number): Reference {
|
||||||
const newRef = new Reference(this.database, this.path, this.query.getModifiers());
|
const newRef = new Reference(this.database, this.path, this.query.getModifiers());
|
||||||
newRef.query.setLimit(name, limit);
|
newRef.query.limit(name, limit);
|
||||||
return newRef;
|
return newRef;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -308,7 +336,7 @@ export default class Reference extends ReferenceBase {
|
||||||
*/
|
*/
|
||||||
filter(name: string, value: any, key?: string): Reference {
|
filter(name: string, value: any, key?: string): Reference {
|
||||||
const newRef = new Reference(this.database, this.path, this.query.getModifiers());
|
const newRef = new Reference(this.database, this.path, this.query.getModifiers());
|
||||||
newRef.query.setFilter(name, value, key);
|
newRef.query.filter(name, value, key);
|
||||||
return newRef;
|
return newRef;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -80,7 +80,7 @@ export default class StorageReference extends ReferenceBase {
|
||||||
* Alias to putFile
|
* Alias to putFile
|
||||||
* @returns {StorageReference.putFile}
|
* @returns {StorageReference.putFile}
|
||||||
*/
|
*/
|
||||||
get put() {
|
get put(): Function {
|
||||||
return this.putFile;
|
return this.putFile;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -11,11 +11,13 @@ declare type UploadTaskSnapshotType = {
|
||||||
downloadURL: string|null,
|
downloadURL: string|null,
|
||||||
metadata: Object, // TODO flow type def for https://firebase.google.com/docs/reference/js/firebase.storage.FullMetadata.html
|
metadata: Object, // TODO flow type def for https://firebase.google.com/docs/reference/js/firebase.storage.FullMetadata.html
|
||||||
ref: StorageReference,
|
ref: StorageReference,
|
||||||
state: StorageStatics.TaskState.RUNNING
|
state: (
|
||||||
|StorageStatics.TaskState.PAUSED
|
typeof StorageStatics.TaskState.RUNNING
|
||||||
|StorageStatics.TaskState.SUCCESS
|
| typeof StorageStatics.TaskState.PAUSED
|
||||||
|StorageStatics.TaskState.CANCELLED
|
| typeof StorageStatics.TaskState.SUCCESS
|
||||||
|StorageStatics.TaskState.ERROR,
|
| typeof StorageStatics.TaskState.CANCELLED
|
||||||
|
| typeof StorageStatics.TaskState.ERROR
|
||||||
|
),
|
||||||
task: StorageTask,
|
task: StorageTask,
|
||||||
totalBytes: number,
|
totalBytes: number,
|
||||||
};
|
};
|
||||||
|
@ -24,15 +26,26 @@ declare type FuncSnapshotType = null|(snapshot: UploadTaskSnapshotType) => any;
|
||||||
|
|
||||||
declare type FuncErrorType = null|(error: Error) => any;
|
declare type FuncErrorType = null|(error: Error) => any;
|
||||||
|
|
||||||
declare type NextOrObserverType = null
|
declare type NextOrObserverType = null |
|
||||||
|{ next?: FuncSnapshotType, error?: FuncErrorType, complete?:FuncSnapshotType }
|
{
|
||||||
|FuncSnapshotType;
|
next?: FuncSnapshotType,
|
||||||
|
error?: FuncErrorType,
|
||||||
|
complete?:FuncSnapshotType
|
||||||
|
} |
|
||||||
|
FuncSnapshotType;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @url https://firebase.google.com/docs/reference/js/firebase.storage.UploadTask
|
* @url https://firebase.google.com/docs/reference/js/firebase.storage.UploadTask
|
||||||
*/
|
*/
|
||||||
export default class StorageTask {
|
export default class StorageTask {
|
||||||
constructor(type: UPLOAD_TASK|DOWNLOAD_TASK, promise: Promise, storageRef: StorageReference) {
|
type: typeof UPLOAD_TASK | typeof DOWNLOAD_TASK
|
||||||
|
ref: StorageReference
|
||||||
|
storage: StorageReference.storage
|
||||||
|
path: StorageReference.path
|
||||||
|
then: Promise<*>
|
||||||
|
catch: () => Promise<*>
|
||||||
|
|
||||||
|
constructor(type: typeof UPLOAD_TASK | typeof DOWNLOAD_TASK, promise: Promise<*>, storageRef: StorageReference) {
|
||||||
this.type = type;
|
this.type = type;
|
||||||
this.ref = storageRef;
|
this.ref = storageRef;
|
||||||
this.storage = storageRef.storage;
|
this.storage = storageRef.storage;
|
||||||
|
@ -49,13 +62,13 @@ export default class StorageTask {
|
||||||
* @returns {Promise.<T>}
|
* @returns {Promise.<T>}
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
_interceptSnapshotEvent(f: Function|null|undefined): null|() => any {
|
_interceptSnapshotEvent(f: ?Function): null | () => * {
|
||||||
if (!isFunction(f)) return null;
|
if (!isFunction(f)) return null;
|
||||||
return (snapshot) => {
|
return (snapshot) => {
|
||||||
const _snapshot = Object.assign({}, snapshot);
|
const _snapshot = Object.assign({}, snapshot);
|
||||||
_snapshot.task = this;
|
_snapshot.task = this;
|
||||||
_snapshot.ref = this.ref;
|
_snapshot.ref = this.ref;
|
||||||
return f(_snapshot);
|
return f && f(_snapshot);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -65,12 +78,13 @@ export default class StorageTask {
|
||||||
* @returns {*}
|
* @returns {*}
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
_interceptErrorEvent(f: Function|null|undefined): null|() => any {
|
_interceptErrorEvent(f: ?Function): null | (Error) => * {
|
||||||
if (!isFunction(f)) return null;
|
if (!isFunction(f)) return null;
|
||||||
return (error) => {
|
return (error) => {
|
||||||
const _error = new Error(error.message);
|
const _error = new Error(error.message);
|
||||||
|
// $FlowFixMe
|
||||||
_error.code = error.code;
|
_error.code = error.code;
|
||||||
return f(_error);
|
return f && f(_error);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -83,15 +97,41 @@ export default class StorageTask {
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
_subscribe(nextOrObserver: NextOrObserverType, error: FuncErrorType, complete: FuncSnapshotType): Function {
|
_subscribe(nextOrObserver: NextOrObserverType, error: FuncErrorType, complete: FuncSnapshotType): Function {
|
||||||
const observer = isObject(nextOrObserver);
|
let _error;
|
||||||
|
let _next;
|
||||||
|
let _complete;
|
||||||
|
|
||||||
const _error = this._interceptErrorEvent(observer ? nextOrObserver.error : error);
|
if (typeof nextOrObserver === 'function') {
|
||||||
const _next = this._interceptSnapshotEvent(observer ? nextOrObserver.next : nextOrObserver);
|
_error = this._interceptErrorEvent(error);
|
||||||
const _complete = this._interceptSnapshotEvent(observer ? nextOrObserver.complete : complete);
|
_next = this._interceptSnapshotEvent(nextOrObserver);
|
||||||
|
_complete = this._interceptSnapshotEvent(complete);
|
||||||
|
} else if (nextOrObserver) {
|
||||||
|
_error = this._interceptErrorEvent(nextOrObserver.error);
|
||||||
|
_next = this._interceptSnapshotEvent(nextOrObserver.next);
|
||||||
|
_complete = this._interceptSnapshotEvent(nextOrObserver.complete);
|
||||||
|
}
|
||||||
|
|
||||||
if (_next) this.storage._addListener(this.path, StorageStatics.TaskEvent.STATE_CHANGED, _next);
|
if (_next) {
|
||||||
if (_error) this.storage._addListener(this.path, `${this.type}_failure`, _error);
|
this.storage._addListener(
|
||||||
if (_complete) this.storage._addListener(this.path, `${this.type}_success`, _complete);
|
this.path,
|
||||||
|
StorageStatics.TaskEvent.STATE_CHANGED,
|
||||||
|
_next
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (_error) {
|
||||||
|
this.storage._addListener(
|
||||||
|
this.path,
|
||||||
|
`${this.type}_failure`,
|
||||||
|
_error
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (_complete) {
|
||||||
|
this.storage._addListener(
|
||||||
|
this.path,
|
||||||
|
`${this.type}_success`,
|
||||||
|
_complete
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
if (_next) this.storage._removeListener(this.path, StorageStatics.TaskEvent.STATE_CHANGED, _next);
|
if (_next) this.storage._removeListener(this.path, StorageStatics.TaskEvent.STATE_CHANGED, _next);
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "react-native-firebase",
|
"name": "react-native-firebase",
|
||||||
"version": "1.0.0-alpha12",
|
"version": "1.0.0-alpha13",
|
||||||
"author": "Invertase <contact@invertase.io> (http://invertase.io)",
|
"author": "Invertase <contact@invertase.io> (http://invertase.io)",
|
||||||
"description": "A react native firebase library supporting both android and ios native firebase SDK's",
|
"description": "A react native firebase library supporting both android and ios native firebase SDK's",
|
||||||
"main": "index",
|
"main": "index",
|
||||||
|
|
|
@ -1,60 +0,0 @@
|
||||||
# OSX
|
|
||||||
#
|
|
||||||
.DS_Store
|
|
||||||
|
|
||||||
# Xcode
|
|
||||||
#
|
|
||||||
build/
|
|
||||||
*.pbxuser
|
|
||||||
!default.pbxuser
|
|
||||||
*.mode1v3
|
|
||||||
!default.mode1v3
|
|
||||||
*.mode2v3
|
|
||||||
!default.mode2v3
|
|
||||||
*.perspectivev3
|
|
||||||
!default.perspectivev3
|
|
||||||
xcuserdata
|
|
||||||
*.xccheckout
|
|
||||||
*.moved-aside
|
|
||||||
DerivedData
|
|
||||||
*.hmap
|
|
||||||
*.ipa
|
|
||||||
*.xcuserstate
|
|
||||||
project.xcworkspace
|
|
||||||
|
|
||||||
# Android/IntelliJ
|
|
||||||
#
|
|
||||||
|
|
||||||
android/gradle
|
|
||||||
.idea
|
|
||||||
.gradle
|
|
||||||
local.properties
|
|
||||||
*.iml
|
|
||||||
|
|
||||||
# node.js
|
|
||||||
#
|
|
||||||
node_modules/
|
|
||||||
ios/Pods
|
|
||||||
npm-debug.log
|
|
||||||
yarn-error.log
|
|
||||||
yarn.lock
|
|
||||||
npm-debug*
|
|
||||||
|
|
||||||
# BUCK
|
|
||||||
buck-out/
|
|
||||||
\.buckd/
|
|
||||||
*.keystore
|
|
||||||
|
|
||||||
# fastlane
|
|
||||||
#
|
|
||||||
# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the
|
|
||||||
# screenshots whenever they are needed.
|
|
||||||
# For more information about the recommended setup visit:
|
|
||||||
# https://github.com/fastlane/fastlane/blob/master/fastlane/docs/Gitignore.md
|
|
||||||
|
|
||||||
fastlane/report.xml
|
|
||||||
fastlane/Preview.html
|
|
||||||
fastlane/screenshots
|
|
||||||
ios/Podfile.lock
|
|
||||||
ios/Pods/
|
|
||||||
ios/ReactNativeFirebaseDemo.xcworkspace/
|
|
Binary file not shown.
|
@ -0,0 +1,6 @@
|
||||||
|
#Tue Mar 07 13:10:12 GMT 2017
|
||||||
|
distributionBase=GRADLE_USER_HOME
|
||||||
|
distributionPath=wrapper/dists
|
||||||
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
|
zipStorePath=wrapper/dists
|
||||||
|
distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip
|
|
@ -36,5 +36,6 @@ target 'ReactNativeFirebaseDemo' do
|
||||||
pod 'Firebase/RemoteConfig'
|
pod 'Firebase/RemoteConfig'
|
||||||
pod 'Firebase/Storage'
|
pod 'Firebase/Storage'
|
||||||
|
|
||||||
|
|
||||||
pod 'RNFirebase', :path => './../../'
|
pod 'RNFirebase', :path => './../../'
|
||||||
end
|
end
|
||||||
|
|
|
@ -0,0 +1,177 @@
|
||||||
|
PODS:
|
||||||
|
- Firebase/Analytics (3.15.0):
|
||||||
|
- Firebase/Core
|
||||||
|
- Firebase/AppIndexing (3.15.0):
|
||||||
|
- Firebase/Core
|
||||||
|
- FirebaseAppIndexing (= 1.2.0)
|
||||||
|
- Firebase/Auth (3.15.0):
|
||||||
|
- Firebase/Core
|
||||||
|
- FirebaseAuth (= 3.1.1)
|
||||||
|
- Firebase/Core (3.15.0):
|
||||||
|
- FirebaseAnalytics (= 3.7.0)
|
||||||
|
- FirebaseCore (= 3.5.2)
|
||||||
|
- Firebase/Crash (3.15.0):
|
||||||
|
- Firebase/Core
|
||||||
|
- FirebaseCrash (= 1.1.6)
|
||||||
|
- Firebase/Database (3.15.0):
|
||||||
|
- Firebase/Core
|
||||||
|
- FirebaseDatabase (= 3.1.2)
|
||||||
|
- Firebase/DynamicLinks (3.15.0):
|
||||||
|
- Firebase/Core
|
||||||
|
- FirebaseDynamicLinks (= 1.3.4)
|
||||||
|
- Firebase/Messaging (3.15.0):
|
||||||
|
- Firebase/Core
|
||||||
|
- FirebaseMessaging (= 1.2.2)
|
||||||
|
- Firebase/RemoteConfig (3.15.0):
|
||||||
|
- Firebase/Core
|
||||||
|
- FirebaseRemoteConfig (= 1.3.4)
|
||||||
|
- Firebase/Storage (3.15.0):
|
||||||
|
- Firebase/Core
|
||||||
|
- FirebaseStorage (= 1.1.0)
|
||||||
|
- FirebaseAnalytics (3.7.0):
|
||||||
|
- FirebaseCore (~> 3.5)
|
||||||
|
- FirebaseInstanceID (~> 1.0)
|
||||||
|
- GoogleToolboxForMac/NSData+zlib (~> 2.1)
|
||||||
|
- FirebaseAppIndexing (1.2.0)
|
||||||
|
- FirebaseAuth (3.1.1):
|
||||||
|
- FirebaseAnalytics (~> 3.7)
|
||||||
|
- GoogleToolboxForMac/NSDictionary+URLArguments (~> 2.1)
|
||||||
|
- GTMSessionFetcher/Core (~> 1.1)
|
||||||
|
- FirebaseCore (3.5.2):
|
||||||
|
- GoogleToolboxForMac/NSData+zlib (~> 2.1)
|
||||||
|
- FirebaseCrash (1.1.6):
|
||||||
|
- FirebaseAnalytics (~> 3.7)
|
||||||
|
- FirebaseInstanceID (~> 1.0)
|
||||||
|
- GoogleToolboxForMac/Logger (~> 2.1)
|
||||||
|
- GoogleToolboxForMac/NSData+zlib (~> 2.1)
|
||||||
|
- Protobuf (~> 3.1)
|
||||||
|
- FirebaseDatabase (3.1.2):
|
||||||
|
- FirebaseAnalytics (~> 3.7)
|
||||||
|
- FirebaseDynamicLinks (1.3.4):
|
||||||
|
- FirebaseAnalytics (~> 3.7)
|
||||||
|
- FirebaseInstanceID (1.0.9)
|
||||||
|
- FirebaseMessaging (1.2.2):
|
||||||
|
- FirebaseAnalytics (~> 3.7)
|
||||||
|
- FirebaseInstanceID (~> 1.0)
|
||||||
|
- GoogleToolboxForMac/Logger (~> 2.1)
|
||||||
|
- Protobuf (~> 3.1)
|
||||||
|
- FirebaseRemoteConfig (1.3.4):
|
||||||
|
- FirebaseAnalytics (~> 3.7)
|
||||||
|
- FirebaseInstanceID (~> 1.0)
|
||||||
|
- GoogleToolboxForMac/NSData+zlib (~> 2.1)
|
||||||
|
- Protobuf (~> 3.1)
|
||||||
|
- FirebaseStorage (1.1.0):
|
||||||
|
- FirebaseAnalytics (~> 3.7)
|
||||||
|
- GTMSessionFetcher/Core (~> 1.1)
|
||||||
|
- GoogleToolboxForMac/DebugUtils (2.1.1):
|
||||||
|
- GoogleToolboxForMac/Defines (= 2.1.1)
|
||||||
|
- GoogleToolboxForMac/Defines (2.1.1)
|
||||||
|
- GoogleToolboxForMac/Logger (2.1.1):
|
||||||
|
- GoogleToolboxForMac/Defines (= 2.1.1)
|
||||||
|
- GoogleToolboxForMac/NSData+zlib (2.1.1):
|
||||||
|
- GoogleToolboxForMac/Defines (= 2.1.1)
|
||||||
|
- GoogleToolboxForMac/NSDictionary+URLArguments (2.1.1):
|
||||||
|
- GoogleToolboxForMac/DebugUtils (= 2.1.1)
|
||||||
|
- GoogleToolboxForMac/Defines (= 2.1.1)
|
||||||
|
- GoogleToolboxForMac/NSString+URLArguments (= 2.1.1)
|
||||||
|
- GoogleToolboxForMac/NSString+URLArguments (2.1.1)
|
||||||
|
- GTMSessionFetcher/Core (1.1.9)
|
||||||
|
- Protobuf (3.2.0)
|
||||||
|
- React (0.40.0):
|
||||||
|
- React/Core (= 0.40.0)
|
||||||
|
- React/Core (0.40.0):
|
||||||
|
- React/cxxreact
|
||||||
|
- React/yoga
|
||||||
|
- React/cxxreact (0.40.0):
|
||||||
|
- React/jschelpers
|
||||||
|
- React/jschelpers (0.40.0)
|
||||||
|
- React/RCTActionSheet (0.40.0):
|
||||||
|
- React/Core
|
||||||
|
- React/RCTAnimation (0.40.0):
|
||||||
|
- React/Core
|
||||||
|
- React/RCTCameraRoll (0.40.0):
|
||||||
|
- React/Core
|
||||||
|
- React/RCTImage
|
||||||
|
- React/RCTGeolocation (0.40.0):
|
||||||
|
- React/Core
|
||||||
|
- React/RCTImage (0.40.0):
|
||||||
|
- React/Core
|
||||||
|
- React/RCTNetwork
|
||||||
|
- React/RCTLinkingIOS (0.40.0):
|
||||||
|
- React/Core
|
||||||
|
- React/RCTNetwork (0.40.0):
|
||||||
|
- React/Core
|
||||||
|
- React/RCTPushNotification (0.40.0):
|
||||||
|
- React/Core
|
||||||
|
- React/RCTSettings (0.40.0):
|
||||||
|
- React/Core
|
||||||
|
- React/RCTText (0.40.0):
|
||||||
|
- React/Core
|
||||||
|
- React/RCTVibration (0.40.0):
|
||||||
|
- React/Core
|
||||||
|
- React/RCTWebSocket (0.40.0):
|
||||||
|
- React/Core
|
||||||
|
- React/yoga (0.40.0)
|
||||||
|
- RNFirebase (1.0.0-alpha12):
|
||||||
|
- Firebase/Auth
|
||||||
|
- Firebase/Core
|
||||||
|
- Firebase/Database
|
||||||
|
- Firebase/Messaging
|
||||||
|
- Firebase/RemoteConfig
|
||||||
|
- Firebase/Storage
|
||||||
|
- React
|
||||||
|
|
||||||
|
DEPENDENCIES:
|
||||||
|
- Firebase/Analytics
|
||||||
|
- Firebase/AppIndexing
|
||||||
|
- Firebase/Auth
|
||||||
|
- Firebase/Core
|
||||||
|
- Firebase/Crash
|
||||||
|
- Firebase/Database
|
||||||
|
- Firebase/DynamicLinks
|
||||||
|
- Firebase/Messaging
|
||||||
|
- Firebase/RemoteConfig
|
||||||
|
- Firebase/Storage
|
||||||
|
- React/Core (from `../node_modules/react-native`)
|
||||||
|
- React/RCTActionSheet (from `../node_modules/react-native`)
|
||||||
|
- React/RCTAnimation (from `../node_modules/react-native`)
|
||||||
|
- React/RCTCameraRoll (from `../node_modules/react-native`)
|
||||||
|
- React/RCTGeolocation (from `../node_modules/react-native`)
|
||||||
|
- React/RCTImage (from `../node_modules/react-native`)
|
||||||
|
- React/RCTLinkingIOS (from `../node_modules/react-native`)
|
||||||
|
- React/RCTNetwork (from `../node_modules/react-native`)
|
||||||
|
- React/RCTPushNotification (from `../node_modules/react-native`)
|
||||||
|
- React/RCTSettings (from `../node_modules/react-native`)
|
||||||
|
- React/RCTText (from `../node_modules/react-native`)
|
||||||
|
- React/RCTVibration (from `../node_modules/react-native`)
|
||||||
|
- React/RCTWebSocket (from `../node_modules/react-native`)
|
||||||
|
- RNFirebase (from `../node_modules/react-native-firebase`)
|
||||||
|
|
||||||
|
EXTERNAL SOURCES:
|
||||||
|
React:
|
||||||
|
:path: "../node_modules/react-native"
|
||||||
|
RNFirebase:
|
||||||
|
:path: "../node_modules/react-native-firebase"
|
||||||
|
|
||||||
|
SPEC CHECKSUMS:
|
||||||
|
Firebase: 2b1cdfba1cda8589f32904a697cc753322bff9d8
|
||||||
|
FirebaseAnalytics: 0d1b7d81d5021155be37702a94ba1ec16d45365d
|
||||||
|
FirebaseAppIndexing: d0fa52ce0ad13f4b5b2f09e4b47fb0dc2213f4e9
|
||||||
|
FirebaseAuth: cc8a1824170adbd351edb7f994490a3fb5c18be6
|
||||||
|
FirebaseCore: a024587e43778508700af8c6b1209f7c4516ba02
|
||||||
|
FirebaseCrash: db4c05d9c75baa050744d31b36357c8f1efba481
|
||||||
|
FirebaseDatabase: 05c96d7b43a7368dc91c07791adb49683e1738d1
|
||||||
|
FirebaseDynamicLinks: 30fb0856dd9ae6d8ba4da00972141a5c293a27b2
|
||||||
|
FirebaseInstanceID: 2d0518b1378fe9d685ef40cbdd63d2fdc1125339
|
||||||
|
FirebaseMessaging: df8267f378580a24174ce7861233aa11d5c90109
|
||||||
|
FirebaseRemoteConfig: af3003f4e8daa2bd1d5cf90d3cccc1fe224f8ed9
|
||||||
|
FirebaseStorage: a5c55b23741a49a72af8f30f95b3bb5ddbeda12d
|
||||||
|
GoogleToolboxForMac: 8e329f1b599f2512c6b10676d45736bcc2cbbeb0
|
||||||
|
GTMSessionFetcher: 5c046c76a1f859bc9c187e918f18e4fc7bb57b5e
|
||||||
|
Protobuf: 745f59e122e5de98d4d7ef291e264a0eef80f58e
|
||||||
|
React: 6dfb2f72edb1d74a800127ae157af038646673ce
|
||||||
|
RNFirebase: 228c16667a3ed1ba3b9ff0702449dca3be1c3618
|
||||||
|
|
||||||
|
PODFILE CHECKSUM: 23445e2727726988c7338fa2f396980d6fd3906f
|
||||||
|
|
||||||
|
COCOAPODS: 1.2.0
|
|
@ -25,7 +25,7 @@ class CoreContainer extends React.Component {
|
||||||
StatusBar.setBackgroundColor('#0279ba');
|
StatusBar.setBackgroundColor('#0279ba');
|
||||||
}
|
}
|
||||||
if (Platform.OS === 'ios') {
|
if (Platform.OS === 'ios') {
|
||||||
StatusBar.setBarStyle('light-content')
|
StatusBar.setBarStyle('light-content');
|
||||||
}
|
}
|
||||||
AppState.addEventListener('change', this.handleAppStateChange);
|
AppState.addEventListener('change', this.handleAppStateChange);
|
||||||
NetInfo.isConnected.fetch().then((isConnected) => {
|
NetInfo.isConnected.fetch().then((isConnected) => {
|
||||||
|
@ -44,6 +44,7 @@ class CoreContainer extends React.Component {
|
||||||
}
|
}
|
||||||
|
|
||||||
props: Props;
|
props: Props;
|
||||||
|
_isConnected: boolean;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handle app state changes
|
* Handle app state changes
|
||||||
|
|
|
@ -1,12 +1,12 @@
|
||||||
|
import { Platform } from 'react-native';
|
||||||
import should from 'should';
|
import should from 'should';
|
||||||
import sinon from 'sinon';
|
import sinon from 'sinon';
|
||||||
|
|
||||||
import DatabaseContents from '../../support/DatabaseContents';
|
import DatabaseContents from '../../support/DatabaseContents';
|
||||||
|
|
||||||
function offTests({ describe, it, xit, xcontext, context, firebase }) {
|
function offTests({ describe, it, xcontext, context, firebase }) {
|
||||||
|
|
||||||
describe('ref().off()', () => {
|
describe('ref().off()', () => {
|
||||||
xit('doesn\'t unbind children callbacks', async () => {
|
it('doesn\'t unbind children callbacks', async () => {
|
||||||
// Setup
|
// Setup
|
||||||
|
|
||||||
const parentCallback = sinon.spy();
|
const parentCallback = sinon.spy();
|
||||||
|
@ -33,7 +33,8 @@ function offTests({ describe, it, xit, xcontext, context, firebase }) {
|
||||||
childCallback.should.be.calledOnce();
|
childCallback.should.be.calledOnce();
|
||||||
|
|
||||||
// Returns nothing
|
// Returns nothing
|
||||||
should(parentRef.off(), undefined);
|
const resp = await parentRef.off();
|
||||||
|
should(resp, undefined);
|
||||||
|
|
||||||
// Trigger event parent callback is listening to
|
// Trigger event parent callback is listening to
|
||||||
await parentRef.set(DatabaseContents.DEFAULT);
|
await parentRef.set(DatabaseContents.DEFAULT);
|
||||||
|
@ -49,7 +50,7 @@ function offTests({ describe, it, xit, xcontext, context, firebase }) {
|
||||||
childCallback.should.be.calledOnce();
|
childCallback.should.be.calledOnce();
|
||||||
|
|
||||||
// Teardown
|
// Teardown
|
||||||
childRef.off();
|
await childRef.off();
|
||||||
});
|
});
|
||||||
|
|
||||||
context('when passed no arguments', () => {
|
context('when passed no arguments', () => {
|
||||||
|
@ -71,15 +72,15 @@ function offTests({ describe, it, xit, xcontext, context, firebase }) {
|
||||||
const arrayLength = DatabaseContents.DEFAULT.array.length;
|
const arrayLength = DatabaseContents.DEFAULT.array.length;
|
||||||
|
|
||||||
await new Promise((resolve) => {
|
await new Promise((resolve) => {
|
||||||
ref.on('value', () => {
|
ref.on('child_added', () => {
|
||||||
valueCallback();
|
childAddedCallback();
|
||||||
resolve();
|
resolve();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
await new Promise((resolve) => {
|
await new Promise((resolve) => {
|
||||||
ref.on('child_added', () => {
|
ref.on('value', () => {
|
||||||
childAddedCallback();
|
valueCallback();
|
||||||
resolve();
|
resolve();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -89,10 +90,15 @@ function offTests({ describe, it, xit, xcontext, context, firebase }) {
|
||||||
|
|
||||||
// Check childAddedCallback is really attached
|
// Check childAddedCallback is really attached
|
||||||
await ref.push(DatabaseContents.DEFAULT.number);
|
await ref.push(DatabaseContents.DEFAULT.number);
|
||||||
|
// TODO: Android: There is definitely a single listener, but value is called three times
|
||||||
|
// rather than the two you'd perhaps expect
|
||||||
|
const expectedCount = Platform.OS === 'ios' ? 2 : 3;
|
||||||
|
valueCallback.should.be.callCount(expectedCount);
|
||||||
childAddedCallback.should.be.callCount(arrayLength + 1);
|
childAddedCallback.should.be.callCount(arrayLength + 1);
|
||||||
|
|
||||||
// Returns nothing
|
// Returns nothing
|
||||||
should(ref.off(), undefined);
|
const resp = await ref.off();
|
||||||
|
should(resp, undefined);
|
||||||
|
|
||||||
// Trigger both callbacks
|
// Trigger both callbacks
|
||||||
|
|
||||||
|
@ -100,7 +106,7 @@ function offTests({ describe, it, xit, xcontext, context, firebase }) {
|
||||||
await ref.push(DatabaseContents.DEFAULT.number);
|
await ref.push(DatabaseContents.DEFAULT.number);
|
||||||
|
|
||||||
// Callbacks should have been unbound and not called again
|
// Callbacks should have been unbound and not called again
|
||||||
valueCallback.should.be.calledOnce();
|
valueCallback.should.be.callCount(expectedCount);
|
||||||
childAddedCallback.should.be.callCount(arrayLength + 1);
|
childAddedCallback.should.be.callCount(arrayLength + 1);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -122,7 +128,7 @@ function offTests({ describe, it, xit, xcontext, context, firebase }) {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
xit('detaches all callbacks listening for that event', async () => {
|
it('detaches all callbacks listening for that event', async () => {
|
||||||
// Setup
|
// Setup
|
||||||
|
|
||||||
const callbackA = sinon.spy();
|
const callbackA = sinon.spy();
|
||||||
|
@ -148,7 +154,8 @@ function offTests({ describe, it, xit, xcontext, context, firebase }) {
|
||||||
callbackB.should.be.calledOnce();
|
callbackB.should.be.calledOnce();
|
||||||
|
|
||||||
// Returns nothing
|
// Returns nothing
|
||||||
should(ref.off('value'), undefined);
|
const resp = await ref.off('value');
|
||||||
|
should(resp, undefined);
|
||||||
|
|
||||||
// Assertions
|
// Assertions
|
||||||
|
|
||||||
|
@ -169,91 +176,111 @@ function offTests({ describe, it, xit, xcontext, context, firebase }) {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
xit('detaches only that callback', async () => {
|
it('detaches only that callback', async () => {
|
||||||
// Setup
|
// Setup
|
||||||
|
let callbackA;
|
||||||
const callbackA = sinon.spy();
|
let callbackB;
|
||||||
const callbackB = sinon.spy();
|
const spyA = sinon.spy();
|
||||||
|
const spyB = sinon.spy();
|
||||||
|
|
||||||
const ref = firebase.native.database().ref('tests/types/string');
|
const ref = firebase.native.database().ref('tests/types/string');
|
||||||
|
|
||||||
// Attach the callback the first time
|
// Attach the callback the first time
|
||||||
await new Promise((resolve) => {
|
await new Promise((resolve) => {
|
||||||
ref.on('value', () => {
|
callbackA = () => {
|
||||||
callbackA();
|
spyA();
|
||||||
resolve();
|
resolve();
|
||||||
});
|
};
|
||||||
|
ref.on('value', callbackA);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Attach the callback the second time
|
// Attach the callback the second time
|
||||||
await new Promise((resolve) => {
|
await new Promise((resolve) => {
|
||||||
ref.on('value', () => {
|
callbackB = () => {
|
||||||
callbackB();
|
spyB();
|
||||||
resolve();
|
resolve();
|
||||||
});
|
};
|
||||||
|
ref.on('value', callbackB);
|
||||||
});
|
});
|
||||||
|
|
||||||
callbackA.should.be.calledOnce();
|
spyA.should.be.calledOnce();
|
||||||
callbackB.should.be.calledOnce();
|
spyB.should.be.calledOnce();
|
||||||
|
|
||||||
// Detach callbackA, only
|
// Detach callbackA, only
|
||||||
should(ref.off('value', callbackA), undefined);
|
const resp = await ref.off('value', callbackA);
|
||||||
|
should(resp, undefined);
|
||||||
|
|
||||||
// Trigger the event the callback is listening to
|
// Trigger the event the callback is listening to
|
||||||
await ref.set(DatabaseContents.DEFAULT.string);
|
await ref.set(DatabaseContents.NEW.string);
|
||||||
|
|
||||||
|
// Add a delay to ensure that the .set() has had time to be registered
|
||||||
|
await new Promise((resolve) => {
|
||||||
|
setTimeout(() => {
|
||||||
|
resolve();
|
||||||
|
}, 1000);
|
||||||
|
});
|
||||||
|
|
||||||
// CallbackB should still be attached
|
// CallbackB should still be attached
|
||||||
callbackA.should.be.calledOnce();
|
spyA.should.be.calledOnce();
|
||||||
callbackB.should.be.calledTwice();
|
spyB.should.be.calledTwice();
|
||||||
|
|
||||||
// Teardown
|
// Teardown
|
||||||
should(ref.off('value', callbackB), undefined);
|
should(ref.off('value', callbackB), undefined);
|
||||||
});
|
});
|
||||||
|
|
||||||
context('that has been added multiple times', () => {
|
context('that has been added multiple times', () => {
|
||||||
xit('must be called as many times completely remove', async () => {
|
it('must be called as many times completely remove', async () => {
|
||||||
// Setup
|
// Setup
|
||||||
|
|
||||||
const callbackA = sinon.spy();
|
const spyA = sinon.spy();
|
||||||
|
let callbackA;
|
||||||
|
|
||||||
const ref = firebase.native.database().ref('tests/types/string');
|
const ref = firebase.native.database().ref('tests/types/string');
|
||||||
|
|
||||||
// Attach the callback the first time
|
// Attach the callback the first time
|
||||||
await new Promise((resolve) => {
|
await new Promise((resolve) => {
|
||||||
ref.on('value', () => {
|
callbackA = () => {
|
||||||
callbackA();
|
spyA();
|
||||||
resolve();
|
resolve();
|
||||||
});
|
};
|
||||||
|
ref.on('value', callbackA);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Attach the callback the second time
|
// Attach the callback the second time
|
||||||
|
ref.on('value', callbackA);
|
||||||
|
|
||||||
|
// Add a delay to ensure that the .on() has had time to be registered
|
||||||
await new Promise((resolve) => {
|
await new Promise((resolve) => {
|
||||||
ref.on('value', () => {
|
setTimeout(() => {
|
||||||
callbackA();
|
|
||||||
resolve();
|
resolve();
|
||||||
});
|
}, 1000);
|
||||||
});
|
});
|
||||||
|
|
||||||
callbackA.should.be.calledTwice();
|
spyA.should.be.calledTwice();
|
||||||
|
|
||||||
// Undo the first time the callback was attached
|
// Undo the first time the callback was attached
|
||||||
should(ref.off(), undefined);
|
const resp = await ref.off('value', callbackA);
|
||||||
|
should(resp, undefined);
|
||||||
|
|
||||||
// Trigger the event the callback is listening to
|
// Trigger the event the callback is listening to
|
||||||
await ref.set(DatabaseContents.DEFAULT.number);
|
await ref.set(DatabaseContents.DEFAULT.number);
|
||||||
|
|
||||||
// Callback should have been called only once because one of the attachments
|
// Callback should have been called only once because one of the attachments
|
||||||
// has been removed
|
// has been removed
|
||||||
callbackA.should.be.calledThrice();
|
// TODO: Android: There is definitely a single listener, but value is called twice
|
||||||
|
// rather than the once you'd perhaps expect
|
||||||
|
const expectedCount = Platform.OS === 'ios' ? 3 : 4;
|
||||||
|
spyA.should.be.callCount(expectedCount);
|
||||||
|
|
||||||
// Undo the second attachment
|
// Undo the second attachment
|
||||||
should(ref.off(), undefined);
|
const resp2 = await ref.off('value', callbackA);
|
||||||
|
should(resp2, undefined);
|
||||||
|
|
||||||
// Trigger the event the callback is listening to
|
// Trigger the event the callback is listening to
|
||||||
await ref.set(DatabaseContents.DEFAULT.number);
|
await ref.set(DatabaseContents.DEFAULT.number);
|
||||||
|
|
||||||
// Callback should not have been called any more times
|
// Callback should not have been called any more times
|
||||||
callbackA.should.be.calledThrice();
|
spyA.should.be.callCount(expectedCount);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
@ -12,7 +12,7 @@ function rootTests({ describe, it, context, firebase }) {
|
||||||
|
|
||||||
// Assertion
|
// Assertion
|
||||||
|
|
||||||
nonRootRef.root.should.eql(rootRef);
|
nonRootRef.root.query.should.eql(rootRef.query);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -27,7 +27,7 @@ function rootTests({ describe, it, context, firebase }) {
|
||||||
|
|
||||||
// Assertion
|
// Assertion
|
||||||
|
|
||||||
rootRef.root.should.eql(rootRef);
|
rootRef.root.query.should.eql(rootRef.query);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
Loading…
Reference in New Issue