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