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/next/lib/api/post.ts
Views: 687
1
import basePath from "lib/base-path";
2
import LRU from "lru-cache";
3
import { join } from "path";
4
5
const VERSION = "v2";
6
7
export default async function apiPost(
8
path: string,
9
data?: object,
10
cache_s: number = 0 // if given, cache results for this many seconds to avoid overfetching
11
): Promise<any> {
12
let cache, key;
13
if (cache_s) {
14
cache = getCache(cache_s);
15
key = JSON.stringify({ path, data });
16
if (cache.has(key)) {
17
return cache.get(key);
18
}
19
}
20
21
const response = await fetch(join(basePath, "api", VERSION, path), {
22
method: "POST",
23
headers: { "Content-Type": "application/json" },
24
body: JSON.stringify(data),
25
});
26
let result;
27
try {
28
result = await response.json();
29
if (result.error) {
30
// if error is set in response, then just throw exception (this greatly simplifies client code).
31
throw Error(result.error);
32
}
33
} catch (err) {
34
if (response.statusText == "Not Found") {
35
throw Error(`The API endpoint ${path} does not exist`);
36
}
37
throw err;
38
}
39
if (cache_s) {
40
cache.set(key, result);
41
}
42
return result;
43
}
44
45
const caches: { [seconds: number]: LRU<string, object> } = {};
46
47
function getCache(seconds: number) {
48
if (!caches[seconds]) {
49
caches[seconds] = new LRU<string, object>({
50
ttl: 1000 * seconds,
51
max: 200,
52
});
53
}
54
return caches[seconds];
55
}
56
57