aegida-console / app / api / me / quota / route.ts
route.ts
Raw
import { AuthError, authenticateRequest } from "@/lib/auth/server";
import { getGateQuota, QuotaError } from "@/lib/chat/quota";
import { isModelId } from "@/lib/chat/types";

const noStoreHeaders = { "Cache-Control": "no-store" };

export async function GET(request: Request): Promise<Response> {
  try {
    await authenticateRequest(request);
    const authorization = request.headers.get("Authorization");
    if (!authorization) throw new AuthError();
    const models = new URL(request.url).searchParams.getAll("model");
    if (models.length !== 1 || !isModelId(models[0])) {
      return Response.json(
        { error: "Некорректный запрос" },
        { status: 400, headers: noStoreHeaders },
      );
    }
    const quota = await getGateQuota(models[0], authorization, request.signal);
    return Response.json({ quota }, { headers: noStoreHeaders });
  } catch (error) {
    const status =
      error instanceof AuthError ||
      (error instanceof QuotaError && error.reason === "unauthorized")
        ? 401
        : 503;
    return Response.json(
      {
        error:
          status === 401
            ? "Unauthorized"
            : "Баланс токенов временно недоступен",
      },
      { status, headers: noStoreHeaders },
    );
  }
}