all files / firebase/utils/ native.js

96% Statements 24/25
83.33% Branches 5/6
100% Functions 5/5
95.83% Lines 23/24
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64                                10× 10×   10× 276× 3607×     10×     3736×   3706× 3706×           30× 30× 30×   30×               30× 10×   20×     30×   30×    
/*
 * @flow
 */
import { NativeModules } from 'react-native';
import { initialiseNativeModuleEventEmitter } from './events';
import INTERNALS from './internals';
 
import type ModuleBase from './ModuleBase';
import type { FirebaseModuleConfig } from '../types';
 
const NATIVE_MODULES: { [string]: Object } = {};
 
/**
 * Prepends appName arg to all native method calls
 * @param appName
 * @param NativeModule
 */
const nativeWithApp = (appName: string, NativeModule: Object): Object => {
  const native = {};
  const methods = Object.keys(NativeModule);
 
  for (let i = 0, len = methods.length; i < len; i++) {
    const method = methods[i];
    native[method] = (...args) => NativeModule[method](...[appName, ...args]);
  }
 
  return native;
};
 
const getModuleKey = (module: ModuleBase): string =>
  `${module.app.name}:${module.namespace}`;
 
export const getNativeModule = (module: ModuleBase): Object => {
  const key = getModuleKey(module);
  return NATIVE_MODULES[key];
};
 
export const initialiseNativeModule = (
  module: ModuleBase,
  config: FirebaseModuleConfig
): Object => {
  const { moduleName, multiApp, namespace } = config;
  const nativeModule = NativeModules[moduleName];
  const key = getModuleKey(module);
 
  Iif (!nativeModule && namespace !== 'utils') {
    throw new Error(
      INTERNALS.STRINGS.ERROR_MISSING_MODULE(namespace, moduleName)
    );
  }
 
  // used by the modules that extend ModuleBase
  // to access their native module counterpart
  if (multiApp) {
    NATIVE_MODULES[key] = nativeWithApp(module.app.name, nativeModule);
  } else {
    NATIVE_MODULES[key] = nativeModule;
  }
 
  initialiseNativeModuleEventEmitter(module, config);
 
  return NATIVE_MODULES[key];
};