Feat: Integrate worker logic as Pages Function

This commit is contained in:
2025-09-26 15:28:39 -07:00
parent 66d000086d
commit 23a11456ed

13
functions/[[path]].js Normal file
View File

@@ -0,0 +1,13 @@
const C='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',L=4,H={'Access-Control-Allow-Origin':'*'}
const r=()=>[...Array(L)].map(()=>C[Math.random()*C.length|0]).join('')
export async function onRequest({request, env}){
if(request.method==='OPTIONS')return new Response(null,{headers:{...H,'Access--Allow-Methods':'POST','Access-Control-Allow-Headers':'Content-Type'}})
const u=new URL(request.url),p=u.pathname.slice(1)
if(request.method==='POST' && !p){try{let{url:t}=await request.json();new URL(t);let s;do s=r();while(await env.EV.get(s)!=null);await env.EV.put(s,t);const d={slug:s,target:t,shortUrl:`${u.origin}/${s}`};return new Response(JSON.stringify(d),{headers:{'Content-Type':'application/json',...H}})}catch(e){return new Response('Invalid URL',{status:400,headers:H})}}
if(p){const t=await env.EV.get(p);if(t)return Response.redirect(t,302)}
return new Response('Not Found',{status:404,headers:H})
}