Skip to content

Commit a86efdf

Browse files
author
Mariusz Pasinski
committed
feat: make the resolveRelativePath() interact with (no-op) require cache
This small change basically introduces "hooks" that can be used to properly implement a require cache
1 parent 16e6655 commit a86efdf

File tree

1 file changed

+25
-14
lines changed

1 file changed

+25
-14
lines changed

packages/react-native-node-api-modules/cpp/CxxNodeApiHostModule.cpp

Lines changed: 25 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -209,24 +209,35 @@ CxxNodeApiHostModule::resolveRelativePath(facebook::jsi::Runtime &rt,
209209
throw jsi::JSError(rt, "Subpath must be relative and cannot leave its package root.");
210210
}
211211

212-
const std::string libraryNameStr(requiredPath);
213-
auto [it, inserted] = nodeAddons_.emplace(libraryNameStr, NodeAddon());
214-
NodeAddon &addon = it->second;
215-
216-
// Check if this module has been loaded already, if not then load it...
217-
if (inserted) {
218-
if (!loadNodeAddon(addon, libraryNameStr)) {
219-
return jsi::Value::undefined();
212+
// Check whether (`requiredPackageName`, `mergedSubpath`) is already cached
213+
// NOTE: Cache must to be `jsi::Runtime`-local
214+
auto [exports, isCached] = lookupRequireCache(rt,
215+
requiredPackageName,
216+
mergedSubpath);
217+
218+
if (!isCached) {
219+
const std::string libraryNameStr(requiredPath);
220+
auto [it, inserted] = nodeAddons_.emplace(libraryNameStr, NodeAddon());
221+
NodeAddon &addon = it->second;
222+
223+
// Check if this module has been loaded already, if not then load it...
224+
if (inserted) {
225+
if (!loadNodeAddon(addon, libraryNameStr)) {
226+
return jsi::Value::undefined();
227+
}
228+
}
229+
230+
// Initialize the addon if it has not already been initialized
231+
if (!rt.global().hasProperty(rt, addon.generatedName.data())) {
232+
initializeNodeModule(rt, addon);
220233
}
221-
}
222234

223-
// Initialize the addon if it has not already been initialized
224-
if (!rt.global().hasProperty(rt, addon.generatedName.data())) {
225-
initializeNodeModule(rt, addon);
235+
// Look up the exports (using JSI), add to cache and return
236+
exports = rt.global().getProperty(rt, addon.generatedName.data());
237+
updateRequireCache(rt, requiredPackageName, mergedSubpath, exports);
226238
}
227239

228-
// Look the exports up (using JSI) and return it...
229-
return rt.global().getProperty(rt, addon.generatedName.data());
240+
return std::move(exports);
230241
}
231242

232243
bool CxxNodeApiHostModule::loadNodeAddon(NodeAddon &addon,

0 commit comments

Comments
 (0)