@taraai/read-write
Version:
Synchronous NoSQL/Firestore for React
219 lines (168 loc) • 8.1 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = createFirebaseInstance;
exports.getFirebase = getFirebase;
var _merge2 = _interopRequireDefault(require("lodash/fp/merge"));
var _isObject2 = _interopRequireDefault(require("lodash/isObject"));
var _utils = require("./utils");
var _actions = require("./utils/actions");
var authActions = _interopRequireWildcard(require("./actions/auth"));
var queryActions = _interopRequireWildcard(require("./actions/query"));
var storageActions = _interopRequireWildcard(require("./actions/storage"));
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
let firebaseInstance;
function createFirebaseInstance(firebase, configs, dispatch) {
if (configs && configs.enableLogging && firebase.database && typeof firebase.database.enableLogging === 'function') {
console.warn('The enableLogging config option is disabled and will be removed in a future version of react-redux-firebase. Enable logging as part of instance initialization.');
firebase.database.enableLogging(configs.enableLogging);
}
const defaultInternals = {
watchers: {},
listeners: {},
callbacks: {},
queries: {},
config: configs,
authUid: null
};
firebase._ = (0, _merge2.default)(defaultInternals, firebase._);
const withMeta = (method, path, value, onComplete) => {
if ((0, _isObject2.default)(value)) {
const prefix = method === 'update' ? 'updated' : 'created';
const dataWithMeta = { ...value,
[`${prefix}At`]: firebase.database.ServerValue.TIMESTAMP
};
if (firebase.auth().currentUser) {
dataWithMeta[`${prefix}By`] = firebase.auth().currentUser.uid;
}
return firebase.database().ref(path)[method](dataWithMeta, onComplete);
}
return firebase.database().ref(path)[method](value, onComplete);
};
const set = (path, value, onComplete) => firebase.database().ref(path).set(value, onComplete);
const setWithMeta = (path, value, onComplete) => withMeta('set', path, value, onComplete);
const push = (path, value, onComplete) => firebase.database().ref(path).push(value, onComplete);
const pushWithMeta = (path, value, onComplete) => withMeta('push', path, value, onComplete);
const update = (path, value, onComplete) => firebase.database().ref(path).update(value, onComplete);
const updateWithMeta = (path, value, onComplete) => withMeta('update', path, value, onComplete);
const remove = (path, onComplete, options) => queryActions.remove(firebase, dispatch, path, options).then(() => {
if (typeof onComplete === 'function') onComplete();
return path;
});
const uniqueSet = (path, value, onComplete) => firebase.database().ref(path).transaction(d => d === null ? value : undefined).then(_ref => {
let {
committed,
snapshot
} = _ref;
if (!committed) {
const newError = new Error('Path already exists.');
if (onComplete) onComplete(newError);
return Promise.reject(newError);
}
if (onComplete) onComplete(snapshot);
return snapshot;
});
const uploadFile = (path, file, dbPath, options) => storageActions.uploadFile(dispatch, firebase, {
path,
file,
dbPath,
options
});
const uploadFiles = (path, files, dbPath, options) => storageActions.uploadFiles(dispatch, firebase, {
path,
files,
dbPath,
options
});
const deleteFile = (path, dbPath) => storageActions.deleteFile(dispatch, firebase, {
path,
dbPath
});
const watchEvent = function (type, path, storeAs) {
let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
return queryActions.watchEvent(firebase, dispatch, {
type,
path,
storeAs,
...options
});
};
const unWatchEvent = function (type, path, queryId) {
let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
return queryActions.unWatchEvent(firebase, dispatch, {
type,
path,
queryId,
...options
});
};
const promiseEvents = (watchArray, options) => {
const inputAsFunc = (0, _utils.createCallable)(watchArray);
const prevData = inputAsFunc(options, firebase);
const queryConfigs = (0, _utils.getEventsFromInput)(prevData);
return Promise.all(queryConfigs.map(queryConfig => queryActions.watchEvent(firebase, dispatch, queryConfig)));
};
const login = credentials => authActions.login(dispatch, firebase, credentials);
const reauthenticate = credentials => authActions.reauthenticate(dispatch, firebase, credentials);
const handleRedirectResult = authData => authActions.handleRedirectResult(dispatch, firebase, authData);
const logout = () => authActions.logout(dispatch, firebase);
const createUser = (credentials, profile) => authActions.createUser(dispatch, firebase, credentials, profile);
const resetPassword = email => authActions.resetPassword(dispatch, firebase, email);
const confirmPasswordReset = (code, password) => authActions.confirmPasswordReset(dispatch, firebase, code, password);
const verifyPasswordResetCode = code => authActions.verifyPasswordResetCode(dispatch, firebase, code);
const applyActionCode = code => authActions.applyActionCode(dispatch, firebase, code);
const updateProfile = (profileUpdate, options) => authActions.updateProfile(dispatch, firebase, profileUpdate, options);
const updateAuth = (authUpdate, updateInProfile) => authActions.updateAuth(dispatch, firebase, authUpdate, updateInProfile);
const updateEmail = (newEmail, updateInProfile) => authActions.updateEmail(dispatch, firebase, newEmail, updateInProfile);
const reloadAuth = () => authActions.reloadAuth(dispatch, firebase);
const linkWithCredential = credential => authActions.linkWithCredential(dispatch, firebase, credential);
const actionCreators = (0, _actions.mapWithFirebaseAndDispatch)(firebase, dispatch, {
signInWithPhoneNumber: authActions.signInWithPhoneNumber
}, {
initializeAuth: authActions.init
});
firebaseInstance = Object.assign(firebase, {
_reactReduxFirebaseExtended: true,
ref: path => firebase.database().ref(path),
set,
setWithMeta,
uniqueSet,
push,
pushWithMeta,
remove,
update,
updateWithMeta,
login,
reauthenticate,
handleRedirectResult,
logout,
updateAuth,
updateEmail,
updateProfile,
uploadFile,
uploadFiles,
deleteFile,
createUser,
resetPassword,
confirmPasswordReset,
verifyPasswordResetCode,
applyActionCode,
watchEvent,
unWatchEvent,
reloadAuth,
linkWithCredential,
promiseEvents,
dispatch,
...actionCreators
});
return firebaseInstance;
}
function getFirebase() {
if (!firebaseInstance) {
throw new Error('Firebase instance does not yet exist. Check your compose function.');
}
return firebaseInstance;
}