UNPKG

2.65 kBPlain TextView Raw
1import Peer, {
2 JsonRpcPayload,
3 JsonRpcPayloadError,
4 JsonRpcPayloadNotification,
5 JsonRpcPayloadRequest,
6 JsonRpcPayloadResponse,
7 // format,
8 MethodNotFound,
9} from 'json-rpc-peer'
10
11// // https://stackoverflow.com/a/50375286/1123955
12// type UnionToIntersection<U> =
13// (U extends any ? (k: U)=>void : never) extends ((k: infer I)=>void) ? I : never
14
15// type UnknownJsonRpcPayload = Partial<UnionToIntersection<JsonRpcPayload>>
16
17const isJsonRpcRequest = (payload: JsonRpcPayload): payload is JsonRpcPayloadRequest => ('method' in payload)
18const isJsonRpcNotification = (payload: JsonRpcPayload): payload is JsonRpcPayloadNotification => isJsonRpcRequest(payload) && (!('id' in payload))
19const isJsonRpcResponse = (payload: JsonRpcPayload): payload is JsonRpcPayloadResponse => ('result' in payload)
20const isJsonRpcError = (payload: JsonRpcPayload): payload is JsonRpcPayloadError => ('error' in payload)
21
22interface IoPeerOptions {
23 serviceGrpcPort: number,
24}
25
26const getPeer = (options: IoPeerOptions) => {
27 const getServiceGrpcPort = () => options.serviceGrpcPort
28
29 const serviceImpl = {
30 /**
31 * Huan(202101) Need to be fixed by new IO Bus system.
32 * See: https://github.com/wechaty/wechaty-puppet-service/issues/118
33 */
34 getHostieGrpcPort: getServiceGrpcPort,
35 }
36
37 const onMessage = async (message: JsonRpcPayload): Promise<any> => {
38 if (isJsonRpcRequest(message)) {
39 const {
40 // id,
41 method,
42 // params,
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 * Huan(202101) Need to be fixed by new IO Bus system.
54 * See: https://github.com/wechaty/wechaty-puppet-service/issues/118
55 */
56 case 'getHostieGrpcPort':
57 return serviceImpl[serviceMethodName]()
58
59 default:
60 throw new MethodNotFound(serviceMethodName)
61 }
62 } else if (isJsonRpcResponse(message)) {
63 // NOOP: we are server
64 } else if (isJsonRpcNotification(message)) {
65 // NOOP: we are server
66 } else if (isJsonRpcError(message)) {
67 // NOOP: we are server
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
79export {
80 getPeer,
81
82 isJsonRpcError,
83 isJsonRpcNotification,
84 isJsonRpcRequest,
85 isJsonRpcResponse,
86}