electron/lib/browser/ipc-main-internal-utils.ts
Samuel Attard 3b74837020 refactor: Split 'Event' docs/types into more specific Event types (#17038)
* Event = Base event type (with preventDefault)
* IpcMainEvent = Event that ipcMain emits (with sender, reply, etc.)
* IpcRendererEvent = Event that ipcRenderer emits (with sender,
senderId, etc.)
* KeyboardEvent = Event that we emit with keyboard flags (ctrlKey,
altKey, etc.)

This will dramatically improve peoples TS experience with IPC events
2019-02-19 09:24:19 +00:00

29 lines
1 KiB
TypeScript

import { ipcMainInternal } from '@electron/internal/browser/ipc-main-internal'
import * as errorUtils from '@electron/internal/common/error-utils'
type IPCHandler = (...args: any[]) => any
const callHandler = async function (handler: IPCHandler, event: ElectronInternal.IpcMainInternalEvent, args: any[], reply: (args: any[]) => void) {
try {
const result = await handler(event, ...args)
reply([null, result])
} catch (error) {
reply([errorUtils.serialize(error)])
}
}
export const handle = function <T extends IPCHandler> (channel: string, handler: T) {
ipcMainInternal.on(channel, (event, requestId, ...args) => {
callHandler(handler, event, args, responseArgs => {
event._replyInternal(`${channel}_RESPONSE_${requestId}`, ...responseArgs)
})
})
}
export const handleSync = function <T extends IPCHandler> (channel: string, handler: T) {
ipcMainInternal.on(channel, (event, ...args) => {
callHandler(handler, event, args, responseArgs => {
event.returnValue = responseArgs
})
})
}