route.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 = () =>
  7. `https://api.cloudflare.com/client/v4/accounts/${serverConfig.cloudflareAccountId}/storage/kv/namespaces/${serverConfig.cloudflareKVNamespaceId}`;
  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 body = {
  15. key: hashedCode,
  16. value: clonedBody,
  17. };
  18. try {
  19. const ttl = parseInt(serverConfig.cloudflareKVTTL);
  20. if (ttl > 60) {
  21. body["expiration_ttl"] = ttl;
  22. }
  23. } catch (e) {
  24. console.error(e);
  25. }
  26. const res = await fetch(`${storeUrl()}/bulk`, {
  27. headers: {
  28. ...storeHeaders(),
  29. "Content-Type": "application/json",
  30. },
  31. method: "PUT",
  32. body: JSON.stringify([body]),
  33. });
  34. const result = await res.json();
  35. console.log("save data", result);
  36. if (result?.success) {
  37. return NextResponse.json(
  38. { code: 0, id: hashedCode, result },
  39. { status: res.status },
  40. );
  41. }
  42. return NextResponse.json(
  43. { error: true, msg: "Save data error" },
  44. { status: 400 },
  45. );
  46. }
  47. if (req.method === "GET") {
  48. const id = req?.nextUrl?.searchParams?.get("id");
  49. const res = await fetch(`${storeUrl()}/values/${id}`, {
  50. headers: storeHeaders(),
  51. method: "GET",
  52. });
  53. return new Response(res.body, {
  54. status: res.status,
  55. statusText: res.statusText,
  56. headers: res.headers,
  57. });
  58. }
  59. return NextResponse.json(
  60. { error: true, msg: "Invalid request" },
  61. { status: 400 },
  62. );
  63. }
  64. export const POST = handle;
  65. export const GET = handle;
  66. export const runtime = "edge";