Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/conat/hub/api/index.ts
1452 views
1
import { isValidUUID } from "@cocalc/util/misc";
2
import { type Purchases, purchases } from "./purchases";
3
import { type System, system } from "./system";
4
import { type Projects, projects } from "./projects";
5
import { type DB, db } from "./db";
6
import { type Jupyter, jupyter } from "./jupyter";
7
import { handleErrorMessage } from "@cocalc/conat/util";
8
9
export interface HubApi {
10
system: System;
11
projects: Projects;
12
db: DB;
13
purchases: Purchases;
14
jupyter: Jupyter;
15
}
16
17
const HubApiStructure = {
18
system,
19
projects,
20
db,
21
purchases,
22
jupyter,
23
} as const;
24
25
export function transformArgs({ name, args, account_id, project_id }) {
26
const [group, functionName] = name.split(".");
27
return HubApiStructure[group]?.[functionName]({
28
args,
29
account_id,
30
project_id,
31
});
32
}
33
34
export function initHubApi(callHubApi): HubApi {
35
const hubApi: any = {};
36
for (const group in HubApiStructure) {
37
if (hubApi[group] == null) {
38
hubApi[group] = {};
39
}
40
for (const functionName in HubApiStructure[group]) {
41
hubApi[group][functionName] = async (...args) => {
42
const resp = await callHubApi({
43
name: `${group}.${functionName}`,
44
args,
45
timeout: args[0]?.timeout,
46
});
47
return handleErrorMessage(resp);
48
};
49
}
50
}
51
return hubApi as HubApi;
52
}
53
54
type UserId =
55
| {
56
account_id: string;
57
project_id: undefined;
58
}
59
| {
60
account_id: undefined;
61
project_id: string;
62
};
63
export function getUserId(subject: string): UserId {
64
const segments = subject.split(".");
65
const uuid = segments[2];
66
if (!isValidUUID(uuid)) {
67
throw Error(`invalid uuid '${uuid}'`);
68
}
69
const type = segments[1]; // 'project' or 'account'
70
if (type == "project") {
71
return { project_id: uuid } as UserId;
72
} else if (type == "account") {
73
return { account_id: uuid } as UserId;
74
} else {
75
throw Error("must be project or account");
76
}
77
}
78
79