-
Notifications
You must be signed in to change notification settings - Fork 6
/
thrift-xhr-request.ts
50 lines (45 loc) · 1.24 KB
/
thrift-xhr-request.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import clients from "./clients";
import ThriftBrowser from "browser-thrift2";
const {
TJSONProtocol,
TBufferedTransport,
createWSConnection,
createXHRConnection,
createClient
} = ThriftBrowser;
/**
* Please replace the host, port, and other options for connecting RPC server
*/
let conn = createXHRConnection("localhost", 9090, {
path: "/thrift/rpc"
});
conn.on("error", err => {
console.dir(err);
});
export default function thriftRPC<T>(method, params): Promise<T> {
let splits: string[] = method.split(".").map(x => x !== "");
if (splits.length < 2) {
throw new Error(
"Invalid RPC method, the correct format is `ServiceName.MethodName`"
);
}
let service = splits[0];
let func = splits[1];
let client = createClient(clients[service], conn);
return new Promise((resolve, reject) => {
try {
client[func](
...Object.keys(params).map(key => params[key]),
(err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
} catch (e) {
reject(e);
}
});
}