Skip to content

Instantly share code, notes, and snippets.

@jtlapp
Last active April 10, 2022 12:53
Show Gist options
  • Save jtlapp/c79e323480793582ac8234d00f58d9e0 to your computer and use it in GitHub Desktop.
Save jtlapp/c79e323480793582ac8234d00f58d9e0 to your computer and use it in GitHub Desktop.
Simplified version of bindMainApi()
export async function bindMainApi<T extends ElectronMainApi<T>>(
apiClassName: string
): Promise<MainApiBinding<T>> {
// Use IPC to get a list of the API's methods from the main process.
const methodNames = await requestApiMethods<T>(apiClassName);
// boundApi will hold the binding, after we've added each method.
const boundApi = {} as MainApiBinding<T>;
// For each method name reported to be in the API...
for (const methodName of methodNames) {
// Assign method an async function that passes its arguments to
// the method's unique IPC channel, waits for the response to
// come back from the server, and returns the return value.
boundApi[methodName] = (async (...args: any[]) => {
const ipcName = `${apiClassName}:${methodName as string}`;
const response = await sendIpcAndGetResponse(ipcName, args);
return response.returnValue;
}) as any; // ('any' makes it compatible with the method's signature)
}
return boundApi;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment