I have written a class that can load scripts from files into the runtime and then can execute those scripts - essentially a plugin system.
class Broker {
constructor(){
this.requests = require("../../plugins/sync/core")
}
}
The scripts will also import this class, as they extend the class's capabilities.
const { Broker } = require("../../core/Broker");
module.exports = {
isConnectableNode: {
minRole: 2,
script: async (data) => {
...
let node = Broker.findNode(data.nodeID); // ERROR: Broker is undefined
...
},
},...
The script is called in this function within the Broker class:
async handleRequest(handler, data, user) {
try {
if (this.requests[handler].minRole >= user.role) {
const res = await this.requests[handler].script(data);
return res;
} else {
return { status: 401, message: "Not authorized." };
}
} catch (e) {
return { status: 400, message: "Unknown Request." };
}
}
What works is calling a function that sets this.requests from within handleRequest() when it is empty or not initialized.
if (!this.requests) this.loadPlugins();
Now all imports are correctly loaded and available to the scripts.
Does anybody know the reason this only works when required from the closure of the handler Function and not the constructor or really anywhere outside?