@rockyf/easy-rpc
v1.0.6
Published
an easy (two ways)rpc impl for window:message or implement by yourself.
Downloads
5
Readme
Easy Rpc
an easy (two ways)rpc impl for window:message or implement by yourself.
Install
yarn add @rockyf/easy-rpc
ornpm i -S @rockyf/eays-rpc
Usage
ES module
import {createRpc, WindowFeederImpl} from '@rockyf/easy-rpc'
COMMONJS module
const {createRpc, WindowFeederImpl} = require('@rockyf/easy-rpc')
UMD module
<script src="https://unpkg.com/@rockyf/easy-rpc@latest/dist/bundle.umd.min.js"></script>
<script>
const {createRpc, WindowFeederImpl} = EasyRpc
</script>
javascript sample
Parent side:
import {createRpc, WindowFeederImpl} from '@rockyf/easy-rpc'
const LOG_TAG = '[Parent]=>'
const iframe = document.getElementById('iframe')
const feeder = new WindowFeederImpl(
'cc',
iframe.contentWindow,
)
feeder.start()
const childRpc = createRpc(
feeder,
{
callParent(payload) {
return new Promise(resolve => {
console.log(LOG_TAG, 'invoke [callParent]:', payload)
setTimeout(() => {
resolve('hello ' + payload)
}, 1000)
})
},
}
)
childRpc.callChild('tom')
.then(
result => {
console.log(LOG_TAG, 'result [callChild]:', result)
}
)
Child side:
import {createRpc, WindowFeederImpl} from '@rockyf/easy-rpc'
const LOG_TAG = '[Child]=>'
const feeder = new WindowFeederImpl(
'cc',
window.parent,
)
feeder.start()
const parentRpc = createRpc(
feeder,
{
callParent(payload) {
console.log(LOG_TAG, 'invoke [callChild]:', payload)
return 'hello ' + payload
},
}
)
parentRpc.callChild('jerry')
.then(
result => {
console.log(LOG_TAG, 'result [callParent]:', result)
}
)
Typescript types
Define remote entity
interface ChildRpc {
callChild(name: string): Promise<string>
}
const childRpc = createRpc<ChildRpc>(
feeder,
{
callParent(payload) {
return new Promise(resolve => {
console.log(LOG_TAG, 'invoke [callParent]:', payload)
setTimeout(() => {
resolve('hello ' + payload)
}, 1000)
})
},
}
)
return type must wrapper with a Promise
Process Error
builtin errors:
- method not found
If error instanceof Error, then it would send its message field
Else send its self
Feeder
Builtin Feeder:
WindowFeederImpl
Communication via window.messageWebsocketFeederImpl
Coming soon❤
Custom Feeder
you could implement feeders by yourself
- just implement
IDataFeeder
interface - call $feedReply method when get message
export class WindowFeederImpl implements IDataFeeder {
...
}