2019-02-14 22:29:20 +00:00
|
|
|
import { EventEmitter } from 'events'
|
2019-05-31 17:25:19 +00:00
|
|
|
import { IpcMainInvokeEvent } from 'electron'
|
2016-01-12 02:40:23 +00:00
|
|
|
|
2019-05-31 17:25:19 +00:00
|
|
|
class IpcMain extends EventEmitter {
|
|
|
|
private _invokeHandlers: Map<string, (e: IpcMainInvokeEvent, ...args: any[]) => void> = new Map();
|
|
|
|
|
|
|
|
handle: Electron.IpcMain['handle'] = (method, fn) => {
|
|
|
|
if (this._invokeHandlers.has(method)) {
|
|
|
|
throw new Error(`Attempted to register a second handler for '${method}'`)
|
|
|
|
}
|
|
|
|
if (typeof fn !== 'function') {
|
|
|
|
throw new Error(`Expected handler to be a function, but found type '${typeof fn}'`)
|
|
|
|
}
|
|
|
|
this._invokeHandlers.set(method, async (e, ...args) => {
|
|
|
|
try {
|
|
|
|
(e as any)._reply(await Promise.resolve(fn(e, ...args)))
|
|
|
|
} catch (err) {
|
|
|
|
(e as any)._throw(err)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
handleOnce: Electron.IpcMain['handleOnce'] = (method, fn) => {
|
|
|
|
this.handle(method, (e, ...args) => {
|
|
|
|
this.removeHandler(method)
|
|
|
|
return fn(e, ...args)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
removeHandler (method: string) {
|
|
|
|
this._invokeHandlers.delete(method)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const ipcMain = new IpcMain()
|
2016-07-24 12:08:25 +00:00
|
|
|
|
|
|
|
// Do not throw exception when channel name is "error".
|
2019-05-31 17:25:19 +00:00
|
|
|
ipcMain.on('error', () => {})
|
2016-12-01 22:43:30 +00:00
|
|
|
|
2019-05-31 17:25:19 +00:00
|
|
|
export default ipcMain
|