Last active
April 9, 2022 20:35
-
-
Save jtlapp/d8003d3db4f38853d90e3c6e39aff544 to your computer and use it in GitHub Desktop.
Simplified implementation of exposeMainApi()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This associates the name of each API with a list of the API's methods. | |
const exposedApis: Record<string, string[]> = {}; | |
function exposeMainApi<T extends ElectronMainApi<T>>(mainApi: T): void { | |
const apiClassName = mainApi.constructor.name; | |
const methodNames: string[] = []; | |
// For each property of mainApi... | |
for (const methodName of getPropertyNames(mainApi)) { | |
// If the property is neither the constructor nor private-prefixed... | |
if (methodName != "constructor" && "_#".indexOf(methodName[0]) < 0) { | |
const method = (mainApi as any)[methodName]; | |
// And if the property is a method of the API... | |
if (typeof method == "function") { | |
// Place the method on an IPC channel whose name includes both the | |
// API's class name and the name of the method. | |
const ipcName = `${apiClassName}:${methodName as string}`; | |
registerIpcHandler(ipcName, (args: any[]) => { | |
// Call the method so that it's 'this' is the mainApi object. | |
return method.bind(mainApi)(...args); | |
}); | |
// Keep track of all the method names in this particular API. | |
methodNames.push(methodName); | |
} | |
} | |
} | |
// Ensure we can look up an API's methods by the API's class name. | |
exposedApis[apiClassName] = methodNames; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment