Skip to content

Instantly share code, notes, and snippets.

@DougAnderson444
Created May 13, 2021 12:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DougAnderson444/7b8d78324126844f6e183b8f5534c432 to your computer and use it in GitHub Desktop.
Save DougAnderson444/7b8d78324126844f6e183b8f5534c432 to your computer and use it in GitHub Desktop.
remote-rpc.js
// import config from "config"; // cant do this until drollup lands
const config = {
"clientDir": "frontend/public",
"port": 8000,
"host": "localhost",
"rpcpath": "rpc-run"
}
const rpcPort = config.port
const rpcHost = config.host
const rpcpath = config.rpcpath
const url = `http://${rpcHost}:${rpcPort}/${rpcpath}`
async function rpc (method, ...params) {
const id = Math.random().toString(36).slice(-6);
console.log(`rpc-run ${method}:`, params)
try {
const payload = { method, params, jsonrpc: '2.0', id }
if ('electron' in window) {
return await window.electron.rpc(payload)
} else {
const response = await fetch(url, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
},
body: JSON.stringify(payload),
})
return await response.json()
}
} catch (e) {
console.log(`rpc-run [fail] ${method} ${e}`)
return { error: { message: `${e}`, code: -32000 }, jsonrpc: '2.0', id }
}
}
class RemoteRpcProxy {
constructor(){
return new Proxy(this, {
get(target, prop) {
return async function() {
return await rpc(prop, ...arguments)
};
}
});
}
}
export const remote = new RemoteRpcProxy();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment