open-index/open-npm huggingface dataset:
npm package: @rockyf/easy-rpc
Description: an easy (two ways)rpc impl for window:message or implement by yourself.
Latest version: 1.0.6

# Easy Rpc

an easy (two ways)rpc impl for window:message or implement by yourself.

## Install

`yarn add @rockyf/easy-rpc`  
or  
`npm 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

```html
<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:

```js
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:

```js
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

```typescript
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.message
* `WebsocketFeederImpl` Coming soon❤

### Custom Feeder

you could implement feeders by yourself

1. just implement `IDataFeeder` interface
2. call $feedReply method when get message

```typescript

export class WindowFeederImpl implements IDataFeeder {
...
}
```