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