electron/lib/renderer/ipc-renderer-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

30 lines
870 B
TypeScript

import { ipcRendererInternal } from '@electron/internal/renderer/ipc-renderer-internal'
import * as errorUtils from '@electron/internal/common/error-utils'
let nextId = 0
export function invoke<T> (command: string, ...args: any[]) {
return new Promise<T>((resolve, reject) => {
const requestId = ++nextId
ipcRendererInternal.once(`${command}_RESPONSE_${requestId}`, (
_event, error: Electron.SerializedError, result: any
) => {
if (error) {
reject(errorUtils.deserialize(error))
} else {
resolve(result)
}
})
ipcRendererInternal.send(command, requestId, ...args)
})
}
export function invokeSync<T> (command: string, ...args: any[]): T {
const [ error, result ] = ipcRendererInternal.sendSync(command, ...args)
if (error) {
throw errorUtils.deserialize(error)
} else {
return result
}
}