2019-02-15 01:24:25 +00:00
|
|
|
import { ipcRendererInternal } from '@electron/internal/renderer/ipc-renderer-internal'
|
2019-02-14 07:05:49 +00:00
|
|
|
import * as errorUtils from '@electron/internal/common/error-utils'
|
|
|
|
|
2019-03-13 19:03:17 +00:00
|
|
|
type IPCHandler = (event: Electron.IpcRendererEvent, ...args: any[]) => any
|
|
|
|
|
|
|
|
export const handle = function <T extends IPCHandler> (channel: string, handler: T) {
|
|
|
|
ipcRendererInternal.on(channel, (event, requestId, ...args) => {
|
|
|
|
new Promise(resolve => resolve(handler(event, ...args))
|
|
|
|
).then(result => {
|
|
|
|
return [null, result]
|
|
|
|
}, error => {
|
|
|
|
return [errorUtils.serialize(error)]
|
|
|
|
}).then(responseArgs => {
|
|
|
|
event.sender.send(`${channel}_RESPONSE_${requestId}`, ...responseArgs)
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2019-02-14 07:05:49 +00:00
|
|
|
let nextId = 0
|
|
|
|
|
|
|
|
export function invoke<T> (command: string, ...args: any[]) {
|
|
|
|
return new Promise<T>((resolve, reject) => {
|
|
|
|
const requestId = ++nextId
|
2019-02-15 01:24:25 +00:00
|
|
|
ipcRendererInternal.once(`${command}_RESPONSE_${requestId}`, (
|
2019-02-19 09:24:19 +00:00
|
|
|
_event, error: Electron.SerializedError, result: any
|
2019-02-14 07:05:49 +00:00
|
|
|
) => {
|
|
|
|
if (error) {
|
|
|
|
reject(errorUtils.deserialize(error))
|
|
|
|
} else {
|
|
|
|
resolve(result)
|
|
|
|
}
|
|
|
|
})
|
2019-02-15 01:24:25 +00:00
|
|
|
ipcRendererInternal.send(command, requestId, ...args)
|
2019-02-14 07:05:49 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
export function invokeSync<T> (command: string, ...args: any[]): T {
|
2019-02-26 23:48:26 +00:00
|
|
|
const [ error, result ] = ipcRendererInternal.sendSync(command, null, ...args)
|
2019-02-14 07:05:49 +00:00
|
|
|
|
|
|
|
if (error) {
|
|
|
|
throw errorUtils.deserialize(error)
|
|
|
|
} else {
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
}
|