88 lines · 3.9 KB
import { HttpError } from "../errors";
import { apiContext } from "./http";
import type { ApiContext } from "./http";
import { createPull, getPull, listPulls, mergePull, updatePullBranch } from "./pulls";
import {
  createRepo,
  deleteRepo,
  forkRepo,
  getCollaborator,
  getRepo,
  importRepo,
  listRepos,
  putCollaborator,
  updateRepo,
} from "./repos";
import { createProtection, listProtections, putContents, setPushProtection } from "./settings";
import { getLfsUsage, getUser, listTokens, revokeToken } from "./user";

export const API_V1_PREFIX = "/api/v1/";

type Handler = (ctx: ApiContext, params: string[]) => Response | Promise<Response>;
type Route = { method: string; pattern: RegExp; handler: Handler };

const SEG = "([^/]+)";
const REPO = `/repos/${SEG}/${SEG}`;

function route(method: string, path: string, handler: Handler): Route {
  return { method, pattern: new RegExp(`^${path}$`), handler };
}

function pullNumber(raw: string): number {
  const number = Number(raw);
  if (!Number.isSafeInteger(number) || number <= 0) throw new HttpError(404, "Pull request not found");
  return number;
}

const ROUTES: Route[] = [
  route("GET", "/user", (ctx) => getUser(ctx)),
  route("GET", "/user/lfs-usage", (ctx) => getLfsUsage(ctx)),
  route("GET", "/user/tokens", (ctx) => listTokens(ctx)),