@@ -4,18 +4,33 @@ import { getServerSideConfig } from "@/app/config/server";
44
55async function handle ( req : NextRequest , res : NextResponse ) {
66 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 } ` ;
99 const storeHeaders = ( ) => ( {
1010 Authorization : `Bearer ${ serverConfig . cloudflareKVApiKey } ` ,
1111 } ) ;
1212 if ( req . method === "POST" ) {
1313 const clonedBody = await req . text ( ) ;
1414 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+ } ,
1732 method : "PUT" ,
18- body : clonedBody ,
33+ body : JSON . stringify ( [ body ] ) ,
1934 } ) ;
2035 const result = await res . json ( ) ;
2136 console . log ( "save data" , result ) ;
@@ -32,7 +47,7 @@ async function handle(req: NextRequest, res: NextResponse) {
3247 }
3348 if ( req . method === "GET" ) {
3449 const id = req ?. nextUrl ?. searchParams ?. get ( "id" ) ;
35- const res = await fetch ( storeUrl ( id as string ) , {
50+ const res = await fetch ( ` ${ storeUrl ( ) } /values/ ${ id } ` , {
3651 headers : storeHeaders ( ) ,
3752 method : "GET" ,
3853 } ) ;
0 commit comments