common.ts 765 B

1234567891011121314151617181920212223242526272829
  1. import { NextRequest } from "next/server";
  2. const OPENAI_URL = "api.openai.com";
  3. const DEFAULT_PROTOCOL = "https";
  4. const PROTOCOL = process.env.PROTOCOL ?? DEFAULT_PROTOCOL;
  5. const BASE_URL = process.env.BASE_URL ?? OPENAI_URL;
  6. export async function requestOpenai(req: NextRequest) {
  7. const apiKey = req.headers.get("token");
  8. const openaiPath = req.headers.get("path");
  9. let baseUrl = BASE_URL;
  10. if (!baseUrl.startsWith("http")) {
  11. baseUrl = `${PROTOCOL}://${baseUrl}`;
  12. }
  13. console.log("[Proxy] ", openaiPath);
  14. console.log("[Base Url]", baseUrl);
  15. return fetch(`${baseUrl}/${openaiPath}`, {
  16. headers: {
  17. "Content-Type": "application/json",
  18. Authorization: `Bearer ${apiKey}`,
  19. },
  20. method: req.method,
  21. body: req.body,
  22. });
  23. }