2020-03-20 13:28:31 -07:00
|
|
|
import { ipcRendererInternal } from '@electron/internal/renderer/ipc-renderer-internal';
|
2019-02-13 23:05:49 -08:00
|
|
|
|
2019-03-13 20:03:17 +01:00
|
|
|
type IPCHandler = (event: Electron.IpcRendererEvent, ...args: any[]) => any
|
|
|
|
|
|
|
|
export const handle = function <T extends IPCHandler> (channel: string, handler: T) {
|
2021-02-09 17:12:26 -08:00
|
|
|
ipcRendererInternal.on(channel, async (event, requestId, ...args) => {
|
2020-03-20 13:28:31 -07:00
|
|
|
const replyChannel = `${channel}_RESPONSE_${requestId}`;
|
2019-08-24 00:45:50 +02:00
|
|
|
try {
|
2020-03-20 13:28:31 -07:00
|
|
|
event.sender.send(replyChannel, null, await handler(event, ...args));
|
2019-08-24 00:45:50 +02:00
|
|
|
} catch (error) {
|
2020-03-20 13:28:31 -07:00
|
|
|
event.sender.send(replyChannel, error);
|
2019-08-24 00:45:50 +02:00
|
|
|
}
|
2020-03-20 13:28:31 -07:00
|
|
|
});
|
|
|
|
};
|
2019-02-13 23:05:49 -08:00
|
|
|
|
|
|
|
export function invokeSync<T> (command: string, ...args: any[]): T {
|
2020-03-20 13:28:31 -07:00
|
|
|
const [error, result] = ipcRendererInternal.sendSync(command, ...args);
|
2019-02-13 23:05:49 -08:00
|
|
|
|
|
|
|
if (error) {
|
2020-03-20 13:28:31 -07:00
|
|
|
throw error;
|
2019-02-13 23:05:49 -08:00
|
|
|
} else {
|
2020-03-20 13:28:31 -07:00
|
|
|
return result;
|
2019-02-13 23:05:49 -08:00
|
|
|
}
|
|
|
|
}
|