2023-06-12 16:39:29 +00:00
|
|
|
import { OpenaiPath } from "@/app/constant";
|
2023-05-14 17:33:46 +00:00
|
|
|
import { prettyObject } from "@/app/utils/format";
|
2023-03-29 17:45:26 +00:00
|
|
|
import { NextRequest, NextResponse } from "next/server";
|
2023-05-03 15:08:37 +00:00
|
|
|
import { auth } from "../../auth";
|
|
|
|
import { requestOpenai } from "../../common";
|
2023-03-29 17:45:26 +00:00
|
|
|
|
2023-06-12 16:39:29 +00:00
|
|
|
const ALLOWD_PATH = new Set(Object.values(OpenaiPath));
|
|
|
|
|
2023-05-03 15:08:37 +00:00
|
|
|
async function handle(
|
|
|
|
req: NextRequest,
|
|
|
|
{ params }: { params: { path: string[] } },
|
|
|
|
) {
|
|
|
|
console.log("[OpenAI Route] params ", params);
|
|
|
|
|
2023-06-14 16:28:47 +00:00
|
|
|
if (req.method === "OPTIONS") {
|
|
|
|
return NextResponse.json({ body: "OK" }, { status: 200 });
|
|
|
|
}
|
|
|
|
|
2023-06-12 16:39:29 +00:00
|
|
|
const subpath = params.path.join("/");
|
|
|
|
|
|
|
|
if (!ALLOWD_PATH.has(subpath)) {
|
|
|
|
console.log("[OpenAI Route] forbidden path ", subpath);
|
|
|
|
return NextResponse.json(
|
|
|
|
{
|
|
|
|
error: true,
|
|
|
|
msg: "you are not allowed to request " + subpath,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
status: 403,
|
|
|
|
},
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2023-05-03 15:08:37 +00:00
|
|
|
const authResult = auth(req);
|
|
|
|
if (authResult.error) {
|
|
|
|
return NextResponse.json(authResult, {
|
|
|
|
status: 401,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2023-03-29 17:45:26 +00:00
|
|
|
try {
|
2023-05-14 17:33:46 +00:00
|
|
|
return await requestOpenai(req);
|
2023-03-29 17:45:26 +00:00
|
|
|
} catch (e) {
|
2023-05-03 09:07:09 +00:00
|
|
|
console.error("[OpenAI] ", e);
|
2023-05-14 17:33:46 +00:00
|
|
|
return NextResponse.json(prettyObject(e));
|
2023-03-29 17:45:26 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-03 15:08:37 +00:00
|
|
|
export const GET = handle;
|
|
|
|
export const POST = handle;
|
2023-04-17 03:36:32 +00:00
|
|
|
|
2023-04-22 17:37:47 +00:00
|
|
|
export const runtime = "edge";
|