@cocalc/hub
Version:
CoCalc: Backend webserver component
82 lines • 3.32 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
/*
The HTTP API, which works via POST requests.
*/
const express_1 = require("express");
const express = __importStar(require("express"));
const { http_message_api_v1 } = require("@cocalc/hub/api/handler");
const async_utils_1 = require("@cocalc/util/async-utils");
const logger_1 = require("@cocalc/hub/logger");
const database_1 = require("../database");
const api_1 = require("@cocalc/server/auth/api");
function init(app_router, projectControl) {
const logger = (0, logger_1.getLogger)("api-server");
logger.info("Initializing API server at /api/v1");
const router = (0, express_1.Router)();
// We need to parse POST requests.
// Note that this can conflict with what is in
// packages/project/servers/browser/http-server.ts
// thus breaking file uploads to projects, so be careful!
// That's why we make a new Router and it only applies
// to the /api/v1 routes. We raise the limit since the
// default is really tiny, and there is an api call to
// upload the contents of a file.
router.use(express.urlencoded({ extended: true, limit: "1mb" }));
router.use(express.json()); // To parse the incoming requests with JSON payloads
router.post("/*", async (req, res) => {
let api_key;
try {
api_key = (0, api_1.getApiKey)(req);
}
catch (err) {
res.status(400).send({ error: err.message });
return;
}
const { body } = req;
const path = req.baseUrl;
const event = path.slice(path.lastIndexOf("/") + 1);
logger.debug(`event=${event}, body=${JSON.stringify(body)}`);
try {
const resp = await (0, async_utils_1.callback2)(http_message_api_v1, {
event,
body,
api_key,
logger,
database: database_1.database,
compute_server: projectControl,
ip_address: req.ip,
});
res.send(resp);
}
catch (err) {
res.status(400).send({ error: `${err}` }); // Bad Request
}
});
app_router.use("/api/v1/*", router);
}
exports.default = init;
//# sourceMappingURL=api.js.map