route.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import md5 from "spark-md5";
  2. import { NextRequest, NextResponse } from "next/server";
  3. import { getServerSideConfig } from "@/app/config/server";
  4. async function handle(req: NextRequest, res: NextResponse) {
  5. const serverConfig = getServerSideConfig();
  6. const storeUrl = (key: string) =>
  7. `https://api.cloudflare.com/client/v4/accounts/${serverConfig.cloudflareAccountId}/storage/kv/namespaces/${serverConfig.cloudflareKVNamespaceId}/values/${key}`;
  8. const storeHeaders = () => ({
  9. Authorization: `Bearer ${serverConfig.cloudflareKVApiKey}`,
  10. });
  11. if (req.method === "POST") {
  12. const clonedBody = await req.text();
  13. const hashedCode = md5.hash(clonedBody).trim();
  14. const res = await fetch(storeUrl(hashedCode), {
  15. headers: storeHeaders(),
  16. method: "PUT",
  17. body: clonedBody,
  18. });
  19. const result = await res.json();
  20. console.log("save data", result);
  21. if (result?.success) {
  22. return NextResponse.json(
  23. { code: 0, id: hashedCode, result },
  24. { status: res.status },
  25. );
  26. }
  27. return NextResponse.json(
  28. { error: true, msg: "Save data error" },
  29. { status: 400 },
  30. );
  31. }
  32. if (req.method === "GET") {
  33. const id = req?.nextUrl?.searchParams?.get("id");
  34. const res = await fetch(storeUrl(id as string), {
  35. headers: storeHeaders(),
  36. method: "GET",
  37. });
  38. return new Response(res.body, {
  39. status: res.status,
  40. statusText: res.statusText,
  41. headers: res.headers,
  42. });
  43. }
  44. return NextResponse.json(
  45. { error: true, msg: "Invalid request" },
  46. { status: 400 },
  47. );
  48. }
  49. export const POST = handle;
  50. export const GET = handle;
  51. export const runtime = "edge";