orb-ui-firebase
Version:
Firebase with redux
111 lines (93 loc) • 3 kB
JavaScript
import * as types from './types';
import * as selectors from './selectors';
import * as initSelectors from '../initialization/selectors';
import { logError } from '../errors/actions';
import { logLoading } from '../loadings/actions';
export var valueChanged = function valueChanged(value, location, path, locationValue) {
return {
type: types.VALUE_CHANGED,
payload: value,
path: path,
location: location,
locationValue: locationValue
};
};
export var destroy = function destroy(location) {
return {
type: types.DESTROY,
location: location
};
};
export var unWatch = function unWatch(path) {
return {
type: types.UNWATCH,
path: path
};
};
export var getRef = function getRef(firebaseApp, path) {
if (typeof path === 'string' || path instanceof String) {
return firebaseApp.firestore().doc(path);
} else {
return path;
}
};
export var getLocation = function getLocation(firebaseApp, path) {
if (typeof path === 'string' || path instanceof String) {
return path;
} else {
return firebaseApp.firestore().doc(path).path;
}
};
export function watchDoc(firebaseApp, firebasePath) {
var reduxPath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var ref = getRef(firebaseApp, firebasePath);
var path = ref.path;
var location = reduxPath || getLocation(firebaseApp, firebasePath);
return function (dispatch, getState) {
var isInitialized = initSelectors.isInitialised(getState(), location);
if (!isInitialized) {
dispatch(logLoading(location));
var unsub = ref.onSnapshot(function (doc) {
dispatch(valueChanged(doc.data(), location, path, unsub));
}, function (err) {
console.error(err);
dispatch(logError(location, err));
});
}
};
}
export function unwatchDoc(firebaseApp, path) {
var reduxPath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
return function (dispatch, getState) {
var location = reduxPath || path;
var allInitializations = selectors.getAllInitializations(getState());
var unsubs = allInitializations[location];
if (unsubs) {
Object.keys(unsubs).map(function (key) {
var unsub = unsubs[key];
if (typeof unsub === 'function') {
unsub();
}
dispatch(unWatch(location));
});
}
};
}
export function destroyDoc(firebaseApp, path) {
var reduxPath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var location = reduxPath || path;
return function (dispatch) {
unwatchDoc(firebaseApp, location);
dispatch(unWatch(location));
dispatch(destroy(location));
};
}
export function unwatchAllDocs(firebaseApp) {
return function (dispatch, getState) {
var allPaths = selectors.getAllDocs(getState());
Object.keys(allPaths).forEach(function (key, index) {
unwatchDoc(firebaseApp, allPaths[index]);
dispatch(unWatch(key));
});
};
}