@@ -4,18 +4,33 @@ import { getServerSideConfig } from "@/app/config/server";
4
4
5
5
async function handle ( req : NextRequest , res : NextResponse ) {
6
6
const serverConfig = getServerSideConfig ( ) ;
7
- const storeUrl = ( key : string ) =>
8
- `https://api.cloudflare.com/client/v4/accounts/${ serverConfig . cloudflareAccountId } /storage/kv/namespaces/${ serverConfig . cloudflareKVNamespaceId } /values/ ${ key } ` ;
7
+ const storeUrl = ( ) =>
8
+ `https://api.cloudflare.com/client/v4/accounts/${ serverConfig . cloudflareAccountId } /storage/kv/namespaces/${ serverConfig . cloudflareKVNamespaceId } ` ;
9
9
const storeHeaders = ( ) => ( {
10
10
Authorization : `Bearer ${ serverConfig . cloudflareKVApiKey } ` ,
11
11
} ) ;
12
12
if ( req . method === "POST" ) {
13
13
const clonedBody = await req . text ( ) ;
14
14
const hashedCode = md5 . hash ( clonedBody ) . trim ( ) ;
15
- const res = await fetch ( storeUrl ( hashedCode ) , {
16
- headers : storeHeaders ( ) ,
15
+ const body = {
16
+ key : hashedCode ,
17
+ value : clonedBody ,
18
+ } ;
19
+ try {
20
+ const ttl = parseInt ( serverConfig . cloudflareKVTTL ) ;
21
+ if ( ttl > 60 ) {
22
+ body [ "expiration_ttl" ] = ttl ;
23
+ }
24
+ } catch ( e ) {
25
+ console . error ( e ) ;
26
+ }
27
+ const res = await fetch ( `${ storeUrl ( ) } /bulk` , {
28
+ headers : {
29
+ ...storeHeaders ( ) ,
30
+ "Content-Type" : "application/json" ,
31
+ } ,
17
32
method : "PUT" ,
18
- body : clonedBody ,
33
+ body : JSON . stringify ( [ body ] ) ,
19
34
} ) ;
20
35
const result = await res . json ( ) ;
21
36
console . log ( "save data" , result ) ;
@@ -32,7 +47,7 @@ async function handle(req: NextRequest, res: NextResponse) {
32
47
}
33
48
if ( req . method === "GET" ) {
34
49
const id = req ?. nextUrl ?. searchParams ?. get ( "id" ) ;
35
- const res = await fetch ( storeUrl ( id as string ) , {
50
+ const res = await fetch ( ` ${ storeUrl ( ) } /values/ ${ id } ` , {
36
51
headers : storeHeaders ( ) ,
37
52
method : "GET" ,
38
53
} ) ;
0 commit comments