electron/lib/renderer/ipc-renderer-internal-utils.ts

25 lines
769 B
TypeScript
Raw Normal View History

2020-03-20 20:28:31 +00:00
import { ipcRendererInternal } from '@electron/internal/renderer/ipc-renderer-internal';
type IPCHandler = (event: Electron.IpcRendererEvent, ...args: any[]) => any
export const handle = function <T extends IPCHandler> (channel: string, handler: T) {
ipcRendererInternal.on(channel, async (event, requestId, ...args) => {
2020-03-20 20:28:31 +00:00
const replyChannel = `${channel}_RESPONSE_${requestId}`;
try {
2020-03-20 20:28:31 +00:00
event.sender.send(replyChannel, null, await handler(event, ...args));
} catch (error) {
2020-03-20 20:28:31 +00:00
event.sender.send(replyChannel, error);
}
2020-03-20 20:28:31 +00:00
});
};
export function invokeSync<T> (command: string, ...args: any[]): T {
2020-03-20 20:28:31 +00:00
const [error, result] = ipcRendererInternal.sendSync(command, ...args);
if (error) {
2020-03-20 20:28:31 +00:00
throw error;
} else {
2020-03-20 20:28:31 +00:00
return result;
}
}