UNPKG

1.3 kBJavaScriptView Raw
1/** Copyright (c) 2018 Uber Technologies, Inc.
2 *
3 * This source code is licensed under the MIT license found in the
4 * LICENSE file in the root directory of this source tree.
5 *
6 * @flow
7 */
8
9import {createPlugin} from 'fusion-core';
10import type {Context} from 'fusion-core';
11import type {Fetch} from 'fusion-tokens';
12import {UniversalEventsToken} from 'fusion-plugin-universal-events';
13
14import MissingHandlerError from './missing-handler-error';
15import {RPCHandlersToken} from './tokens';
16import type {HandlerType} from './tokens.js';
17import type {RPCPluginType, IEmitter} from './types.js';
18
19class RPC {
20 ctx: ?Context;
21 emitter: ?IEmitter;
22 handlers: ?HandlerType;
23 fetch: ?Fetch;
24
25 constructor(handlers: any) {
26 this.handlers = handlers;
27 }
28
29 async request<TArgs, TResult>(method: string, args: TArgs): Promise<TResult> {
30 if (!this.handlers) {
31 throw new Error('fusion-plugin-rpc requires `handlers`');
32 }
33
34 if (!this.handlers[method]) {
35 throw new MissingHandlerError(method);
36 }
37 return this.handlers[method](args);
38 }
39}
40
41const plugin: RPCPluginType = createPlugin({
42 deps: {
43 handlers: RPCHandlersToken,
44 emitter: UniversalEventsToken,
45 },
46 provides: ({handlers} = {}) => {
47 return {from: () => new RPC(handlers)};
48 },
49});
50
51export default plugin;