Merge pull request #34 from Leeds-eBooks/patch/flow-errors-1

Fixing various flow errors
This commit is contained in:
Michael Diarmid 2017-04-04 23:30:04 +01:00 committed by GitHub
commit f6ee3ff6f9
10 changed files with 117 additions and 40 deletions

View File

@ -15,7 +15,7 @@ import Messaging, { statics as MessagingStatics } from './modules/messaging';
import Analytics from './modules/analytics'; import Analytics from './modules/analytics';
import Crash from './modules/crash'; import Crash from './modules/crash';
const instances = { default: null }; const instances: Object = { default: null };
const FirebaseModule = NativeModules.RNFirebase; const FirebaseModule = NativeModules.RNFirebase;
/** /**
@ -34,6 +34,19 @@ export default class Firebase {
_remoteConfig: ?Object; _remoteConfig: ?Object;
_crash: ?Object; _crash: ?Object;
auth: Function;
storage: Function;
database: Function;
messaging: Function;
eventHandlers: Object;
debug: boolean;
options: {
errorOnMissingPlayServices: boolean,
debug?: boolean,
persistence?: boolean
};
/** /**
* *
* @param options * @param options
@ -127,14 +140,17 @@ export default class Firebase {
* @returns {function()} * @returns {function()}
* @private * @private
*/ */
_staticsOrInstance(name, statics, InstanceClass) { _staticsOrInstance(name, statics, InstanceClass): Function {
const getInstance = () => { const getInstance = () => {
const internalPropName = `_${name}`; const internalPropName = `_${name}`;
// $FlowFixMe
if (!this[internalPropName]) { if (!this[internalPropName]) {
// $FlowFixMe
this[internalPropName] = new InstanceClass(this); this[internalPropName] = new InstanceClass(this);
} }
// $FlowFixMe
return this[internalPropName]; return this[internalPropName];
}; };

View File

@ -21,3 +21,13 @@ declare type GoogleApiAvailabilityType = {
isUserResolvableError?: boolean, isUserResolvableError?: boolean,
error?: string error?: string
}; };
declare class FirebaseError {
message: string,
name: string,
code: string,
stack: string,
path: string,
details: string,
modifiers: string
};

View File

@ -42,7 +42,12 @@ export default class Auth extends Base {
if (auth && auth.user && !this._user) this._user = new User(this, auth); if (auth && auth.user && !this._user) this._user = new User(this, auth);
else if ((!auth || !auth.user) && this._user) this._user = null; else if ((!auth || !auth.user) && this._user) this._user = null;
else if (this._user) this._user._updateValues(auth); else if (this._user) this._user._updateValues(auth);
if (emit) this.emit('onAuthStateChanged', this._authResult.user || null); if (emit) {
this.emit(
'onAuthStateChanged',
this._authResult && this._authResult.user || null
);
}
return auth ? this._user : null; return auth ? this._user : null;
} }

View File

@ -33,7 +33,7 @@ export default class Analytics extends Base {
* @param {Error} error * @param {Error} error
* @param maxStackSize * @param maxStackSize
*/ */
report(error: Error, maxStackSize: Number = 10): void { report(error: FirebaseError, maxStackSize: number = 10): void {
if (!error || !error.code || !error.message) return; if (!error || !error.code || !error.message) return;
let errorMessage = `Message: ${error.message}\r\n`; let errorMessage = `Message: ${error.message}\r\n`;

View File

@ -12,6 +12,7 @@ const FirebaseDatabase = NativeModules.RNFirebaseDatabase;
*/ */
export default class Disconnect { export default class Disconnect {
ref: Reference; ref: Reference;
path: string;
/** /**
* *

View File

@ -218,7 +218,8 @@ export default class Database extends Base {
firebaseMessage = `${firebaseMessage} at /${path}\r\n`; firebaseMessage = `${firebaseMessage} at /${path}\r\n`;
} }
const firebaseError = new Error(firebaseMessage); // $FlowFixMe
const firebaseError: FirebaseError = new Error(firebaseMessage);
firebaseError.code = code; firebaseError.code = code;
firebaseError.path = path; firebaseError.path = path;

View File

@ -157,19 +157,25 @@ export default class Reference extends ReferenceBase {
* @param onComplete * @param onComplete
* @param applyLocally * @param applyLocally
*/ */
transaction(transactionUpdate, onComplete?: () => any, applyLocally: boolean = false) { transaction(
transactionUpdate: Function,
onComplete?: (?Error, any, ?Snapshot) => any,
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) => {
const onCompleteWrapper = (error, committed, snapshotData) => { const onCompleteWrapper = (error, committed, snapshotData) => {
if (error) { if (error) {
if (isFunction(onComplete)) onComplete(error, committed, null); if (typeof onComplete === 'function') {
onComplete(error, committed, null);
}
return reject(error); return reject(error);
} }
const snapshot = new Snapshot(this, snapshotData); const snapshot = new Snapshot(this, snapshotData);
if (isFunction(onComplete)) { if (typeof onComplete === 'function') {
onComplete(null, committed, snapshot); onComplete(null, committed, snapshot);
} }

View File

@ -62,7 +62,7 @@ export default class Snapshot {
* @link https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#exists * @link https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#exists
* @returns {boolean} * @returns {boolean}
*/ */
exists(): Boolean { exists(): boolean {
return this._value !== null; return this._value !== null;
} }
@ -71,7 +71,7 @@ export default class Snapshot {
* @link https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#forEach * @link https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#forEach
* @param action * @param action
*/ */
forEach(action: (key: any) => any): Boolean { forEach(action: (key: any) => any): boolean {
if (!this._childKeys.length) return false; if (!this._childKeys.length) return false;
let cancelled = false; let cancelled = false;
@ -94,7 +94,7 @@ export default class Snapshot {
* @link https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#getPriority * @link https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#getPriority
* @returns {String|Number|null} * @returns {String|Number|null}
*/ */
getPriority(): String|Number|null { getPriority(): string | number | null {
return this._priority; return this._priority;
} }
@ -104,7 +104,7 @@ export default class Snapshot {
* @param path * @param path
* @returns {Boolean} * @returns {Boolean}
*/ */
hasChild(path: string): Boolean { hasChild(path: string): boolean {
return deepExists(this._value, path); return deepExists(this._value, path);
} }
@ -113,7 +113,7 @@ export default class Snapshot {
* @link https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#hasChildren * @link https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#hasChildren
* @returns {boolean} * @returns {boolean}
*/ */
hasChildren(): Boolean { hasChildren(): boolean {
return this.numChildren() > 0; return this.numChildren() > 0;
} }
@ -122,7 +122,7 @@ export default class Snapshot {
* @link https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#numChildren * @link https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#numChildren
* @returns {Number} * @returns {Number}
*/ */
numChildren(): Number { numChildren(): number {
if (!isObject(this._value)) return 0; if (!isObject(this._value)) return 0;
return Object.keys(this._value).length; return Object.keys(this._value).length;
} }

View File

@ -13,7 +13,7 @@ const FirebaseDatabase = NativeModules.RNFirebaseDatabase;
* @class Database * @class Database
*/ */
export default class TransactionHandler extends Base { export default class TransactionHandler extends Base {
constructor(firebase: Object, database: Object, FirebaseDatabaseEvt) { constructor(firebase: Object, database: Object, FirebaseDatabaseEvt: Object) {
super(firebase, {}); super(firebase, {});
this.transactions = {}; this.transactions = {};
this.database = database; this.database = database;
@ -32,7 +32,12 @@ export default class TransactionHandler extends Base {
* @param onComplete * @param onComplete
* @param applyLocally * @param applyLocally
*/ */
add(reference, transactionUpdater, onComplete, applyLocally = false) { add(
reference: Object,
transactionUpdater: Function,
onComplete?: Function,
applyLocally?: boolean = false
) {
const id = this._generateTransactionId(); const id = this._generateTransactionId();
this.transactions[id] = { this.transactions[id] = {
@ -45,7 +50,7 @@ export default class TransactionHandler extends Base {
started: true, started: true,
}; };
FirebaseDatabase.startTransaction(reference.path, id, applyLocally || false); FirebaseDatabase.startTransaction(reference.path, id, applyLocally);
} }
/** /**
@ -57,7 +62,7 @@ export default class TransactionHandler extends Base {
* @returns {string} * @returns {string}
* @private * @private
*/ */
_generateTransactionId() { _generateTransactionId(): string {
return generatePushID(this.database.serverTimeOffset); return generatePushID(this.database.serverTimeOffset);
} }
@ -72,7 +77,7 @@ export default class TransactionHandler extends Base {
case 'update': case 'update':
return this._handleUpdate(event); return this._handleUpdate(event);
case 'error': case 'error':
return this._handleError(error); return this._handleError(event);
case 'complete': case 'complete':
return this._handleComplete(event); return this._handleComplete(event);
default: default:

View File

@ -1,3 +1,6 @@
/**
* @flow
*/
// modeled after base64 web-safe chars, but ordered by ASCII // modeled after base64 web-safe chars, but ordered by ASCII
const PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz'; const PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
const hasOwnProperty = Object.hasOwnProperty; const hasOwnProperty = Object.hasOwnProperty;
@ -8,7 +11,8 @@ const _handler = (resolve, reject, errorPrefix, err, resp) => {
// resolve / reject after events etc // resolve / reject after events etc
setImmediate(() => { setImmediate(() => {
if (err) { if (err) {
const firebaseError = new Error(err.message); // $FlowFixMe
const firebaseError: FirebaseError = new Error(err.message);
if (isObject(err)) { if (isObject(err)) {
Object.keys(err).forEach(key => Object.defineProperty(firebaseError, key, { value: err[key] })); Object.keys(err).forEach(key => Object.defineProperty(firebaseError, key, { value: err[key] }));
@ -23,7 +27,7 @@ const _handler = (resolve, reject, errorPrefix, err, resp) => {
}); });
}; };
export function toWebSDKErrorCode(code, prefix) { export function toWebSDKErrorCode(code: any, prefix: string): string {
if (!code || typeof code !== 'string') return ''; if (!code || typeof code !== 'string') return '';
return code.toLowerCase().replace('error_', prefix).replace(/_/g, '-'); return code.toLowerCase().replace('error_', prefix).replace(/_/g, '-');
} }
@ -36,7 +40,11 @@ export function toWebSDKErrorCode(code, prefix) {
* @param joiner * @param joiner
* @returns {*} * @returns {*}
*/ */
export function deepGet(object, path, joiner = '/') { export function deepGet(
object: Object,
path: string,
joiner?: string = '/'
): any {
const keys = path.split(joiner); const keys = path.split(joiner);
let i = 0; let i = 0;
@ -60,7 +68,11 @@ export function deepGet(object, path, joiner = '/') {
* @param joiner * @param joiner
* @returns {*} * @returns {*}
*/ */
export function deepExists(object, path, joiner = '/') { export function deepExists(
object: Object,
path: string,
joiner?: string = '/'
): boolean {
const keys = path.split(joiner); const keys = path.split(joiner);
let i = 0; let i = 0;
@ -81,7 +93,7 @@ export function deepExists(object, path, joiner = '/') {
* @param item * @param item
* @returns {boolean} * @returns {boolean}
*/ */
export function isObject(item) { export function isObject(item: any): boolean {
return (item && typeof item === 'object' && !Array.isArray(item) && item !== null); return (item && typeof item === 'object' && !Array.isArray(item) && item !== null);
} }
@ -90,8 +102,8 @@ export function isObject(item) {
* @param item * @param item
* @returns {*|boolean} * @returns {*|boolean}
*/ */
export function isFunction(item) { export function isFunction(item?: any): boolean {
return (item && typeof item === 'function'); return Boolean(item && typeof item === 'function');
} }
/** /**
@ -99,9 +111,9 @@ export function isFunction(item) {
* @param string * @param string
* @returns {*} * @returns {*}
*/ */
export function tryJSONParse(string) { export function tryJSONParse(string: string | null): any {
try { try {
return JSON.parse(string); return string && JSON.parse(string);
} catch (jsonError) { } catch (jsonError) {
return string; return string;
} }
@ -112,7 +124,7 @@ export function tryJSONParse(string) {
* @param data * @param data
* @returns {*} * @returns {*}
*/ */
export function tryJSONStringify(data) { export function tryJSONStringify(data: any): string | null {
try { try {
return JSON.stringify(data); return JSON.stringify(data);
} catch (jsonError) { } catch (jsonError) {
@ -149,7 +161,11 @@ export function noop(): void {
* @param NativeModule * @param NativeModule
* @param errorPrefix * @param errorPrefix
*/ */
export function promisify(fn: Function, NativeModule: Object, errorPrefix): Function<Promise> { export function promisify(
fn: Function | string,
NativeModule: Object,
errorPrefix?: string
): (any) => Promise<> {
return (...args) => { return (...args) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const _fn = typeof fn === 'function' ? fn : NativeModule[fn]; const _fn = typeof fn === 'function' ? fn : NativeModule[fn];
@ -168,7 +184,12 @@ export function promisify(fn: Function, NativeModule: Object, errorPrefix): Func
* @param callback * @param callback
* @private * @private
*/ */
function _delayChunk(collection, chunkSize, operation, callback): void { function _delayChunk(
collection: Array<*>,
chunkSize: number,
operation: Function,
callback: Function
): void {
const length = collection.length; const length = collection.length;
const iterations = Math.ceil(length / chunkSize); const iterations = Math.ceil(length / chunkSize);
@ -196,21 +217,28 @@ function _delayChunk(collection, chunkSize, operation, callback): void {
* @param iterator * @param iterator
* @param cb * @param cb
*/ */
export function each(array: Array, chunkSize?: number, iterator: Function, cb: Function): void { export function each(
array: Array<*>,
chunkSize: number | Function,
iterator: Function,
cb?: Function
): void {
if (typeof chunkSize === 'function') { if (typeof chunkSize === 'function') {
cb = iterator; cb = iterator;
iterator = chunkSize; iterator = chunkSize;
chunkSize = DEFAULT_CHUNK_SIZE; chunkSize = DEFAULT_CHUNK_SIZE;
} }
if (cb) {
_delayChunk(array, chunkSize, (slice, start) => { _delayChunk(array, chunkSize, (slice, start) => {
for (let ii = 0, jj = slice.length; ii < jj; ii += 1) { for (let ii = 0, jj = slice.length; ii < jj; ii += 1) {
iterator(slice[ii], start + ii); iterator(slice[ii], start + ii);
} }
}, cb); }, cb);
} }
}
export function typeOf(value) { export function typeOf(value: any): string {
if (value === null) return 'null'; if (value === null) return 'null';
if (Array.isArray(value)) return 'array'; if (Array.isArray(value)) return 'array';
return typeof value; return typeof value;
@ -224,7 +252,12 @@ export function typeOf(value) {
* @param cb * @param cb
* @returns {*} * @returns {*}
*/ */
export function map(array: Array, chunkSize?: number, iterator: Function, cb: Function): void { export function map(
array: Array<*>,
chunkSize: number | Function,
iterator: Function,
cb?: Function
): void {
if (typeof chunkSize === 'function') { if (typeof chunkSize === 'function') {
cb = iterator; cb = iterator;
iterator = chunkSize; iterator = chunkSize;
@ -237,7 +270,7 @@ export function map(array: Array, chunkSize?: number, iterator: Function, cb: Fu
result.push(iterator(slice[ii], start + ii, array)); result.push(iterator(slice[ii], start + ii, array));
} }
return result; return result;
}, () => cb(result)); }, () => cb && cb(result));
} }