route.ts 2.0 KB

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