ipc-main-impl.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { EventEmitter } from 'events';
  2. import { IpcMainInvokeEvent } from 'electron/main';
  3. export class IpcMainImpl extends EventEmitter {
  4. private _invokeHandlers: Map<string, (e: IpcMainInvokeEvent, ...args: any[]) => void> = new Map();
  5. constructor () {
  6. super();
  7. // Do not throw exception when channel name is "error".
  8. this.on('error', () => {});
  9. }
  10. handle: Electron.IpcMain['handle'] = (method, fn) => {
  11. if (this._invokeHandlers.has(method)) {
  12. throw new Error(`Attempted to register a second handler for '${method}'`);
  13. }
  14. if (typeof fn !== 'function') {
  15. throw new Error(`Expected handler to be a function, but found type '${typeof fn}'`);
  16. }
  17. this._invokeHandlers.set(method, async (e, ...args) => {
  18. try {
  19. e._reply(await Promise.resolve(fn(e, ...args)));
  20. } catch (err) {
  21. e._throw(err as Error);
  22. }
  23. });
  24. }
  25. handleOnce: Electron.IpcMain['handleOnce'] = (method, fn) => {
  26. this.handle(method, (e, ...args) => {
  27. this.removeHandler(method);
  28. return fn(e, ...args);
  29. });
  30. }
  31. removeHandler (method: string) {
  32. this._invokeHandlers.delete(method);
  33. }
  34. }