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