1 | import Peer, {
|
2 | JsonRpcPayload,
|
3 | JsonRpcPayloadError,
|
4 | JsonRpcPayloadNotification,
|
5 | JsonRpcPayloadRequest,
|
6 | JsonRpcPayloadResponse,
|
7 |
|
8 | MethodNotFound,
|
9 | } from 'json-rpc-peer'
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | const isJsonRpcRequest = (payload: JsonRpcPayload): payload is JsonRpcPayloadRequest => ('method' in payload)
|
18 | const isJsonRpcNotification = (payload: JsonRpcPayload): payload is JsonRpcPayloadNotification => isJsonRpcRequest(payload) && (!('id' in payload))
|
19 | const isJsonRpcResponse = (payload: JsonRpcPayload): payload is JsonRpcPayloadResponse => ('result' in payload)
|
20 | const isJsonRpcError = (payload: JsonRpcPayload): payload is JsonRpcPayloadError => ('error' in payload)
|
21 |
|
22 | interface IoPeerOptions {
|
23 | serviceGrpcPort: number,
|
24 | }
|
25 |
|
26 | const getPeer = (options: IoPeerOptions) => {
|
27 | const getServiceGrpcPort = () => options.serviceGrpcPort
|
28 |
|
29 | const serviceImpl = {
|
30 | |
31 |
|
32 |
|
33 |
|
34 | getHostieGrpcPort: getServiceGrpcPort,
|
35 | }
|
36 |
|
37 | const onMessage = async (message: JsonRpcPayload): Promise<any> => {
|
38 | if (isJsonRpcRequest(message)) {
|
39 | const {
|
40 |
|
41 | method,
|
42 |
|
43 | } = message
|
44 |
|
45 | if (!(method in serviceImpl)) {
|
46 | console.error('serviceImpl does not contain method: ' + method)
|
47 | return
|
48 | }
|
49 |
|
50 | const serviceMethodName = method as keyof typeof serviceImpl
|
51 | switch (serviceMethodName) {
|
52 | |
53 |
|
54 |
|
55 |
|
56 | case 'getHostieGrpcPort':
|
57 | return serviceImpl[serviceMethodName]()
|
58 |
|
59 | default:
|
60 | throw new MethodNotFound(serviceMethodName)
|
61 | }
|
62 | } else if (isJsonRpcResponse(message)) {
|
63 |
|
64 | } else if (isJsonRpcNotification(message)) {
|
65 |
|
66 | } else if (isJsonRpcError(message)) {
|
67 |
|
68 | } else {
|
69 | throw new Error('unknown json-rpc message: ' + JSON.stringify(message))
|
70 | }
|
71 | console.info(JSON.stringify(message))
|
72 | }
|
73 |
|
74 | const ioPeer = new Peer(onMessage)
|
75 |
|
76 | return ioPeer
|
77 | }
|
78 |
|
79 | export {
|
80 | getPeer,
|
81 |
|
82 | isJsonRpcError,
|
83 | isJsonRpcNotification,
|
84 | isJsonRpcRequest,
|
85 | isJsonRpcResponse,
|
86 | }
|