|
|
@@ -4,18 +4,33 @@ import { getServerSideConfig } from "@/app/config/server";
|
|
|
|
|
|
async function handle(req: NextRequest, res: NextResponse) {
|
|
|
const serverConfig = getServerSideConfig();
|
|
|
- const storeUrl = (key: string) =>
|
|
|
- `https://api.cloudflare.com/client/v4/accounts/${serverConfig.cloudflareAccountId}/storage/kv/namespaces/${serverConfig.cloudflareKVNamespaceId}/values/${key}`;
|
|
|
+ const storeUrl = () =>
|
|
|
+ `https://api.cloudflare.com/client/v4/accounts/${serverConfig.cloudflareAccountId}/storage/kv/namespaces/${serverConfig.cloudflareKVNamespaceId}`;
|
|
|
const storeHeaders = () => ({
|
|
|
Authorization: `Bearer ${serverConfig.cloudflareKVApiKey}`,
|
|
|
});
|
|
|
if (req.method === "POST") {
|
|
|
const clonedBody = await req.text();
|
|
|
const hashedCode = md5.hash(clonedBody).trim();
|
|
|
- const res = await fetch(storeUrl(hashedCode), {
|
|
|
- headers: storeHeaders(),
|
|
|
+ const body = {
|
|
|
+ key: hashedCode,
|
|
|
+ value: clonedBody,
|
|
|
+ };
|
|
|
+ try {
|
|
|
+ const ttl = parseInt(serverConfig.cloudflareKVTTL);
|
|
|
+ if (ttl > 60) {
|
|
|
+ body["expiration_ttl"] = ttl;
|
|
|
+ }
|
|
|
+ } catch (e) {
|
|
|
+ console.error(e);
|
|
|
+ }
|
|
|
+ const res = await fetch(`${storeUrl()}/bulk`, {
|
|
|
+ headers: {
|
|
|
+ ...storeHeaders(),
|
|
|
+ "Content-Type": "application/json",
|
|
|
+ },
|
|
|
method: "PUT",
|
|
|
- body: clonedBody,
|
|
|
+ body: JSON.stringify([body]),
|
|
|
});
|
|
|
const result = await res.json();
|
|
|
console.log("save data", result);
|
|
|
@@ -32,7 +47,7 @@ async function handle(req: NextRequest, res: NextResponse) {
|
|
|
}
|
|
|
if (req.method === "GET") {
|
|
|
const id = req?.nextUrl?.searchParams?.get("id");
|
|
|
- const res = await fetch(storeUrl(id as string), {
|
|
|
+ const res = await fetch(`${storeUrl()}/values/${id}`, {
|
|
|
headers: storeHeaders(),
|
|
|
method: "GET",
|
|
|
});
|