pfrazee / pauls-electron-rpc

My RPC solution for exporting APIs from the electron background process to renderers and webviews
37 stars 7 forks source link
electron

pauls-electron-rpc

Features:

Example usage

In a shared example-api-manifest.js:

module.exports = {
  // simple method-types
  readFile: 'async',
  readFileSync: 'sync',
  sayHello: 'promise',
  createReadStream: 'readable',
  createWriteStream: 'writable',
  createDuplexStream: 'duplex'
}

In the main electron process:

var rpc = require('pauls-electron-rpc')
var manifest = require('./example-api-manifest')
var fs = require('fs')

// export over the 'example-api' channel
var api = rpc.exportAPI('example-api', manifest, {
  // the exported API behaves like normal calls:
  readFile: fs.readFile,
  readFileSync: fs.readFileSync,
  sayHello: () => return Promise.resolve('hello!'),
  createReadStream: fs.createReadStream,
  createWriteStream: /* ... */,
  createDuplexStream: /* ... */
})

// log any errors
api.on('error', console.log)

In the renderer or webview process:

var rpc = require('pauls-electron-rpc')
var manifest = require('./example-api-manifest')

// import over the 'example-api' channel
var api = rpc.importAPI('example-api', manifest, { timeout: 30e3 })

// now use, as usual:
api.readFileSync('/etc/hosts') // => '...'

API

rpc.exportAPI(channelName, manifest, methods, [globalPermissionCheck])

Methods will be called with a this set to the event object from electron ipc. Don't touch returnValue.

You can optionally specify a method for globalPermissionCheck with the following signature:

function globalPermissionCheck (event, methodName, args) {
  if (event.sender.getURL() != 'url-I-trust') return false
  return true
}

If globalPermissionCheck is specified, and does not return true, the method call will respond with a 'Denied' error.

rpc.importAPI(channelName, manifest [,options])

Readable Streams

Readable streams in the clientside are given a .close() method. All serverside streams MUST implement .close() or .destroy(), either of which will be called.

Stream methods can return a promise that resolves to a stream.

Buffers and ArrayBuffers

Arguments and return values are massaged so that they are Buffers on the exporter's side, and ArrayBuffers on the importer side.

Custom Errors

// shared code
// =

var manifest = {
  testThrow: 'promise'
}

class MyCustomError extends Error {
  constructor() {
    super()
    this.name = 'MyCustomError'
    this.message = 'Custom error!'
  }
}

// server
// =

rpc.exportAPI('error-api', manifest, {
  testThrow() {
    return Promise.reject(new MyCustomError())
  }
})

// client
// =

var rpcClient = rpc.importAPI('error-api', manifest, {
  errors: {MyCustomError} // pass in custom error constructors
})
rpcClient.testThrow().catch(console.log) // => MyCustomError