JSINativeModules.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. #include "jsireact/JSINativeModules.h"
  8. #include <glog/logging.h>
  9. #include <cxxreact/ReactMarker.h>
  10. #include <jsi/JSIDynamic.h>
  11. #include <string>
  12. using namespace facebook::jsi;
  13. namespace facebook {
  14. namespace react {
  15. JSINativeModules::JSINativeModules(
  16. std::shared_ptr<ModuleRegistry> moduleRegistry)
  17. : m_moduleRegistry(std::move(moduleRegistry)) {}
  18. Value JSINativeModules::getModule(Runtime &rt, const PropNameID &name) {
  19. if (!m_moduleRegistry) {
  20. return nullptr;
  21. }
  22. std::string moduleName = name.utf8(rt);
  23. const auto it = m_objects.find(moduleName);
  24. if (it != m_objects.end()) {
  25. return Value(rt, it->second);
  26. }
  27. auto module = createModule(rt, moduleName);
  28. if (!module.hasValue()) {
  29. // Allow lookup to continue in the objects own properties, which allows for
  30. // overrides of NativeModules
  31. return nullptr;
  32. }
  33. auto result =
  34. m_objects.emplace(std::move(moduleName), std::move(*module)).first;
  35. return Value(rt, result->second);
  36. }
  37. void JSINativeModules::reset() {
  38. m_genNativeModuleJS = folly::none;
  39. m_objects.clear();
  40. }
  41. folly::Optional<Object> JSINativeModules::createModule(
  42. Runtime &rt,
  43. const std::string &name) {
  44. bool hasLogger(ReactMarker::logTaggedMarker);
  45. if (hasLogger) {
  46. ReactMarker::logTaggedMarker(
  47. ReactMarker::NATIVE_MODULE_SETUP_START, name.c_str());
  48. }
  49. if (!m_genNativeModuleJS) {
  50. m_genNativeModuleJS =
  51. rt.global().getPropertyAsFunction(rt, "__fbGenNativeModule");
  52. }
  53. auto result = m_moduleRegistry->getConfig(name);
  54. if (!result.hasValue()) {
  55. return folly::none;
  56. }
  57. Value moduleInfo = m_genNativeModuleJS->call(
  58. rt,
  59. valueFromDynamic(rt, result->config),
  60. static_cast<double>(result->index));
  61. CHECK(!moduleInfo.isNull()) << "Module returned from genNativeModule is null";
  62. folly::Optional<Object> module(
  63. moduleInfo.asObject(rt).getPropertyAsObject(rt, "module"));
  64. if (hasLogger) {
  65. ReactMarker::logTaggedMarker(
  66. ReactMarker::NATIVE_MODULE_SETUP_STOP, name.c_str());
  67. }
  68. return module;
  69. }
  70. } // namespace react
  71. } // namespace facebook