1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 | import {createPlugin} from 'fusion-core';
|
10 | import type {Context} from 'fusion-core';
|
11 | import type {Fetch} from 'fusion-tokens';
|
12 | import {UniversalEventsToken} from 'fusion-plugin-universal-events';
|
13 |
|
14 | import MissingHandlerError from './missing-handler-error';
|
15 | import {RPCHandlersToken} from './tokens';
|
16 | import type {HandlerType} from './tokens.js';
|
17 | import type {RPCPluginType, IEmitter} from './types.js';
|
18 |
|
19 | class 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 |
|
41 | const plugin: RPCPluginType = createPlugin({
|
42 | deps: {
|
43 | handlers: RPCHandlersToken,
|
44 | emitter: UniversalEventsToken,
|
45 | },
|
46 | provides: ({handlers} = {}) => {
|
47 | return {from: () => new RPC(handlers)};
|
48 | },
|
49 | });
|
50 |
|
51 | export default plugin;
|