Fetch data on the server and client with an RPC style interface.
If you're using React, you should use fusion-plugin-rpc-react
instead of this package. If you're also using Redux, you should use fusion-plugin-rpc-redux-react
.
yarn add fusion-plugin-rpc
// src/main.js
import React from 'react';
import App from 'fusion-react';
import RPC from 'fusion-plugin-rpc';
import fetch from 'unfetch';
// Define your rpc methods server side
const handlers = __NODE__ && {
getUser: async (args, ctx) => {
return {some: 'data' + args};
},
};
export default () => {
const app = new App(<div></div>);
const Api = app.plugin(RPC, {handlers, fetch});
app.plugin((ctx, next) => {
Api.of(ctx).request('getUser', 1).then(console.log) // {some: 'data1'}
});
return app;
}
const Api = app.plugin(RPC, {handlers, fetch, EventEmitter});
handlers: Object<(...args: any) => Promise>
- Server-only. Required. A map of server-side RPC method implementationsfetch: (url: string, options: Object) => Promise
- Browser-only. Required. Afetch
implementationEventEmitter
- Server-only. Optional. An event emitter plugin such as fusion-plugin-universal-events
const instance = Api.of(ctx)
instance.request(method: string, args: any)
- make an rpc call to themethod
handler withargs
.
If on the server, this will directly call the method
handler with (args, ctx)
.
If on the browser, this will POST
to /api/${method}
endpoint with JSON serialized args as the request body. The server will then deserialize the args and call the rpc handler. The response will be serialized and send back to the browser.