Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/src/packages/hub/servers/app/api.ts
Views: 687
/*1The HTTP API, which works via POST requests.2*/3import { Router } from "express";4import * as express from "express";5const { http_message_api_v1 } = require("@cocalc/hub/api/handler");6import { callback2 } from "@cocalc/util/async-utils";7import { getLogger } from "@cocalc/hub/logger";8import { database } from "../database";9import { ProjectControlFunction } from "@cocalc/server/projects/control";10import { getApiKey } from "@cocalc/server/auth/api";1112export default function init(13app_router: Router,14projectControl: ProjectControlFunction15) {16const logger = getLogger("api-server");17logger.info("Initializing API server at /api/v1");1819const router = Router();2021// We need to parse POST requests.22// Note that this can conflict with what is in23// packages/project/servers/browser/http-server.ts24// thus breaking file uploads to projects, so be careful!25// That's why we make a new Router and it only applies26// to the /api/v1 routes. We raise the limit since the27// default is really tiny, and there is an api call to28// upload the contents of a file.29router.use(express.urlencoded({ extended: true, limit: "1mb" }));30router.use(express.json()); // To parse the incoming requests with JSON payloads3132router.post("/*", async (req, res) => {33let api_key;34try {35api_key = getApiKey(req);36} catch (err) {37res.status(400).send({ error: err.message });38return;39}40const { body } = req;41const path = req.baseUrl;42const event = path.slice(path.lastIndexOf("/") + 1);43logger.debug(`event=${event}, body=${JSON.stringify(body)}`);44try {45const resp = await callback2(http_message_api_v1, {46event,47body,48api_key,49logger,50database,51projectControl,52ip_address: req.ip,53});54res.send(resp);55} catch (err) {56res.status(400).send({ error: `${err}` }); // Bad Request57}58});5960app_router.use("/api/v1/*", router);61}626364