Created
August 4, 2017 19:47
-
-
Save BrandonSmith/c02149d87e503b437d6a9d46710ce4ef to your computer and use it in GitHub Desktop.
Electron `call` interface between main and renderer processes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { ipcMain } from 'electron' | |
import uuid from 'uuid' | |
/** | |
* Makes a data request over IPC to renderer process | |
* @param {string} request Request type known to main handler | |
* @param {object} Optional `options` object used as parameters for request | |
* @return {Promise} Promise of data | |
*/ | |
export function call(window, request, options={}) { | |
return new Promise((resolve, reject) => { | |
const id = uuid.v1() | |
ipcMain.once(`response:${id`, (_, response) => { | |
respose.success ? | |
resolve(response.data) : | |
reject(response.data) | |
}) | |
window.webContents.send(`request`, { id, context: { request, options } }) | |
}) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { ipcRenderer } from 'electron' | |
ipcRenderer.on(`request`, handleRequest) | |
async function handleRequest(_, { id, context: { request, options } }) { | |
const { sendSuccess, sendError } = prepareResponse(sender, requestId) | |
switch(request) { | |
case `ping`: | |
await doSomeAsyncWork() | |
sendSuccess(`Hello, ${options.hello}. I'm done.`) | |
default: | |
sendError(`Unsupported request: ${request}`) | |
} | |
} | |
function prepareResponse(id) { | |
return { | |
sendSuccess: data => ipcRenderer.send(`response:${id}`, { success: true, data }), | |
sendError: error => ipcRenderer.send(`response:${id}`, { success: false, error }) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment