2020-03-20 20:28:31 +00:00
|
|
|
import { EventEmitter } from 'events';
|
|
|
|
import { IpcMainInvokeEvent } from 'electron';
|
2019-08-23 22:45:50 +00:00
|
|
|
|
|
|
|
export class IpcMainImpl extends EventEmitter {
|
|
|
|
private _invokeHandlers: Map<string, (e: IpcMainInvokeEvent, ...args: any[]) => void> = new Map();
|
|
|
|
|
|
|
|
handle: Electron.IpcMain['handle'] = (method, fn) => {
|
|
|
|
if (this._invokeHandlers.has(method)) {
|
2020-03-20 20:28:31 +00:00
|
|
|
throw new Error(`Attempted to register a second handler for '${method}'`);
|
2019-08-23 22:45:50 +00:00
|
|
|
}
|
|
|
|
if (typeof fn !== 'function') {
|
2020-03-20 20:28:31 +00:00
|
|
|
throw new Error(`Expected handler to be a function, but found type '${typeof fn}'`);
|
2019-08-23 22:45:50 +00:00
|
|
|
}
|
|
|
|
this._invokeHandlers.set(method, async (e, ...args) => {
|
|
|
|
try {
|
2020-03-20 20:28:31 +00:00
|
|
|
(e as any)._reply(await Promise.resolve(fn(e, ...args)));
|
2019-08-23 22:45:50 +00:00
|
|
|
} catch (err) {
|
2020-03-20 20:28:31 +00:00
|
|
|
(e as any)._throw(err);
|
2019-08-23 22:45:50 +00:00
|
|
|
}
|
2020-03-20 20:28:31 +00:00
|
|
|
});
|
2019-08-23 22:45:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
handleOnce: Electron.IpcMain['handleOnce'] = (method, fn) => {
|
|
|
|
this.handle(method, (e, ...args) => {
|
2020-03-20 20:28:31 +00:00
|
|
|
this.removeHandler(method);
|
|
|
|
return fn(e, ...args);
|
|
|
|
});
|
2019-08-23 22:45:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
removeHandler (method: string) {
|
2020-03-20 20:28:31 +00:00
|
|
|
this._invokeHandlers.delete(method);
|
2019-08-23 22:45:50 +00:00
|
|
|
}
|
|
|
|
}
|