ipc-main-impl.ts 1.0 KB

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