CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/sync/client/call.ts
Views: 687
1
/*
2
A handy utility function for implementing an api using the project websocket.
3
*/
4
5
import { callback } from "awaiting";
6
import type { ProjectWebsocket } from "./types";
7
8
export default async function call(
9
conn: ProjectWebsocket,
10
mesg: object,
11
timeout_ms: number,
12
) {
13
const resp = await callback(call0, conn, mesg, timeout_ms);
14
if (resp?.status == "error") {
15
throw Error(resp.error);
16
}
17
return resp;
18
}
19
20
function call0(
21
conn: ProjectWebsocket,
22
mesg: object,
23
timeout_ms: number,
24
cb: Function,
25
): void {
26
let done: boolean = false;
27
let timer: any = 0;
28
if (timeout_ms) {
29
timer = setTimeout(function () {
30
if (done) return;
31
done = true;
32
cb("timeout");
33
}, timeout_ms);
34
}
35
36
const t = Date.now();
37
conn.writeAndWait(mesg, function (resp) {
38
if (conn.verbose) {
39
console.log(`call finished ${Date.now() - t}ms`, mesg, resp);
40
}
41
if (done) {
42
return;
43
}
44
done = true;
45
if (timer) {
46
clearTimeout(timer);
47
}
48
cb(undefined, resp);
49
});
50
}
51
52