CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/hub/servers/app/api.ts
Views: 687
1
/*
2
The HTTP API, which works via POST requests.
3
*/
4
import { Router } from "express";
5
import * as express from "express";
6
const { http_message_api_v1 } = require("@cocalc/hub/api/handler");
7
import { callback2 } from "@cocalc/util/async-utils";
8
import { getLogger } from "@cocalc/hub/logger";
9
import { database } from "../database";
10
import { ProjectControlFunction } from "@cocalc/server/projects/control";
11
import { getApiKey } from "@cocalc/server/auth/api";
12
13
export default function init(
14
app_router: Router,
15
projectControl: ProjectControlFunction
16
) {
17
const logger = getLogger("api-server");
18
logger.info("Initializing API server at /api/v1");
19
20
const router = Router();
21
22
// We need to parse POST requests.
23
// Note that this can conflict with what is in
24
// packages/project/servers/browser/http-server.ts
25
// thus breaking file uploads to projects, so be careful!
26
// That's why we make a new Router and it only applies
27
// to the /api/v1 routes. We raise the limit since the
28
// default is really tiny, and there is an api call to
29
// upload the contents of a file.
30
router.use(express.urlencoded({ extended: true, limit: "1mb" }));
31
router.use(express.json()); // To parse the incoming requests with JSON payloads
32
33
router.post("/*", async (req, res) => {
34
let api_key;
35
try {
36
api_key = getApiKey(req);
37
} catch (err) {
38
res.status(400).send({ error: err.message });
39
return;
40
}
41
const { body } = req;
42
const path = req.baseUrl;
43
const event = path.slice(path.lastIndexOf("/") + 1);
44
logger.debug(`event=${event}, body=${JSON.stringify(body)}`);
45
try {
46
const resp = await callback2(http_message_api_v1, {
47
event,
48
body,
49
api_key,
50
logger,
51
database,
52
projectControl,
53
ip_address: req.ip,
54
});
55
res.send(resp);
56
} catch (err) {
57
res.status(400).send({ error: `${err}` }); // Bad Request
58
}
59
});
60
61
app_router.use("/api/v1/*", router);
62
}
63
64