Pastery

BackBlaze CloudFlare worker script +

 1const b2Domain = 'yourdomain.com'; 2const b2Bucket = 'your-bucket-name'; 3 4const b2UrlPath = `/file/${b2Bucket}/`; 5 6addEventListener('fetch', event => { 7    return event.respondWith(fileReq(event)); 8}); 910// define the file extensions we wish to add basic access control headers to11const corsFileTypes = ['png', 'jpg', 'gif', 'jpeg', 'webp'];1213// backblaze returns some additional headers that are useful for debugging, but unecessary in production. We can remove these to save some size14const removeHeaders = [15    'x-bz-content-sha1',16    'x-bz-file-id',17    'x-bz-file-name',18    'x-bz-info-src_last_modified_millis',19    'X-Bz-Upload-Timestamp'20];2122async function fileReq(event) {23    if (event.request.method != 'GET') {24        return new Response('Method not allowed', {25            status: 40526        })27    }2829    const cache = caches.default30    const url = new URL(event.request.url);3132    let response = await cache.match(url)33    if (response) {34        return response;35    }3637    if (url.host === b2Domain && !url.pathname.startsWith(b2UrlPath)) {38        url.pathname = b2UrlPath + url.pathname;39    }4041    // fetch image, apply Cloudflare lossless compression42    response = await fetch(url, {43        cf: {44            polish: "lossless"45        }46    });47    let newHdrs = new Headers(response.headers);48    if (corsFileTypes.includes(url.pathname.split('.').pop())) {49        newHdrs.set('Access-Control-Allow-Origin', '*');50    }51    newHdrs.set('cache-control', 'public, max-age=31536000');52    removeHeaders.forEach((header) => {53        newHdrs.delete(header);54    });5556    if (response.status > 399) {57        return new Response(response.statusText, {58            status: response.status59        })60    }6162    response = new Response(response.body, {63        status: response.status,64        statusText: response.statusText,65        headers: newHdrs66    });67    event.waitUntil(cache.put(url, response.clone()))68    return response;69}
New paste