Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.4 kB
4
Indexable
Never
addEventListener('fetch', event => {

    event.respondWith(purgeCache(event.request))

})

async function purgeCache(request) {

    const url = new URL(request.url)
    const hostname = url.searchParams.get('hostname');

    // If the path doesn't begin with our protected prefix, just pass the request through.
    if (!url.pathname.startsWith("/__purge_cache")) {
        return fetch(request)
    }

    // Lets validate the zone id, and return an error if invalid
    let zoneIdValidated = (new RegExp("^([a-z0-9]{32})$")).test(url.searchParams.get('zone'));

    if (!zoneIdValidated) {
        return new Response('Invalid Zone ID', {
          status: 500
        });
    }


    let content = '{"files":["https://'+ hostname +'/","https://'+ hostname +'/page/1/","https://'+ hostname +'/page/2/","https://'+ hostname +'/page/3/","https://'+ hostname +'/page/4/","https://'+ hostname +'/page/5/"]}'
    let headers = {
        'Content-Type': 'application/json',
        'X-Auth-Email': 'EMAIL', // Cloudflare API Auth Email
        'X-Auth-Key': 'AAPI' //Cloudflare API Auth Key
    }

    const init = {
        method: 'POST',
        headers: headers,
        body: content
    }
    
    const response = await fetch('https://api.cloudflare.com/client/v4/zones/'+url.searchParams.get('zone')+'/purge_cache', init)

    return response
}