ipc-main-impl.ts 1.0 KB

12345678910111213141516171819202122232425262728293031323334
  1. import { EventEmitter } from 'events';
  2. import { IpcMainInvokeEvent } from 'electron/main';
  3. export class IpcMainImpl extends EventEmitter implements Electron.IpcMain {
  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 TypeError(`Expected handler to be a function, but found type '${typeof fn}'`);
  16. }
  17. this._invokeHandlers.set(method, fn);
  18. };
  19. handleOnce: Electron.IpcMain['handleOnce'] = (method, fn) => {
  20. this.handle(method, (e, ...args) => {
  21. this.removeHandler(method);
  22. return fn(e, ...args);
  23. });
  24. };
  25. removeHandler (method: string) {
  26. this._invokeHandlers.delete(method);
  27. }
  28. }