Last active
August 4, 2022 13:43
-
-
Save sahilrajput03/a08e4347f7acccc38ee90770bc0b16a7 to your computer and use it in GitHub Desktop.
rpc-demo snippet FRONTEND
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
<!-- File: index.html --> | |
<!-- In <body> of you html, you can use rpc like that --> | |
<div class="desc">Use below buttons to call appropriate function on server:</div> | |
<button onclick="btn1()">rpc.test()</button> | |
<button onclick="btn2()">rpc.yoy("God loves all")</button> | |
<button onclick="btn3()">rpc.cat({say: "meoww"})</button> | |
<button onclick="btn4()">rpc.love("donald", "pikachu")</button> | |
<button onclick="btn5()">rpc.someNonExistingFunction("pokemons")</button> | |
<button onclick="btn6()">rpc.rain("Charlizard", "Nobita")</button> | |
<script> | |
const log = console.log | |
// STEP1: Setup RPC client | |
const rpc = createRpc('/rpc') | |
// STEP2: Attach click handlers | |
async function btn1() { | |
const data = await rpc.test() | |
log(data) | |
} | |
async function btn2() { | |
const data = await rpc.yoy('God loves all') | |
log(data) | |
} | |
async function btn3() { | |
const data = await rpc.cat({say: 'meoww'}) | |
log(data) | |
} | |
async function btn4() { | |
const data = await rpc.love('donald', 'pikachu') | |
log(data) | |
} | |
async function btn5() { | |
try { | |
const res = await rpc.someNonExistingFunction('pokemons') | |
} catch (error) { | |
const {name, message, status} = error | |
log('CAUGHT ERROR: \n' + ['name: ' + name, 'message: ' + message, 'status: ' + status].join('\n\n')) | |
} | |
} | |
async function btn6() { | |
try { | |
const res = await rpc.rain('Charlizard', 'Nobita') | |
log(res) | |
} catch (error) { | |
const {name, message, status} = error | |
log('CAUGHT ERROR: \n' + ['name: ' + name, 'message: ' + message, 'status: ' + status].join('\n\n')) | |
} | |
} | |
// Utility function to create our rpc client | |
function createRpc(url) { | |
const target = {} | |
const handler = { | |
get(target, prop) { | |
return async (...functionParams) => { | |
if (!url.endsWith('/')) { | |
url = url + '/' | |
} | |
return await axios | |
.post(`${url}${prop}`, functionParams) | |
.then((response) => response.data) | |
.catch((e) => { | |
throw {...e.response.data, status: e.response.status} | |
}) | |
} | |
}, | |
} | |
return new Proxy(target, handler) | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment