Pastery

BackBlaze CloudFlare worker script +

const b2Domain = 'yourdomain.com';
const b2Bucket = 'your-bucket-name';

const b2UrlPath = `/file/${b2Bucket}/`;

addEventListener('fetch', event => {
    return event.respondWith(fileReq(event));
});

// define the file extensions we wish to add basic access control headers to
const corsFileTypes = ['png', 'jpg', 'gif', 'jpeg', 'webp'];

// backblaze returns some additional headers that are useful for debugging, but unecessary in production. We can remove these to save some size
const removeHeaders = [
    'x-bz-content-sha1',
    'x-bz-file-id',
    'x-bz-file-name',
    'x-bz-info-src_last_modified_millis',
    'X-Bz-Upload-Timestamp'
];

async function fileReq(event) {
    if (event.request.method != 'GET') {
        return new Response('Method not allowed', {
            status: 405
        })
    }

    const cache = caches.default
    const url = new URL(event.request.url);

    let response = await cache.match(url)
    if (response) {
        return response;
    }

    if (url.host === b2Domain && !url.pathname.startsWith(b2UrlPath)) {
        url.pathname = b2UrlPath + url.pathname;
    }

    // fetch image, apply Cloudflare lossless compression
    response = await fetch(url, {
        cf: {
            polish: "lossless"
        }
    });
    let newHdrs = new Headers(response.headers);
    if (corsFileTypes.includes(url.pathname.split('.').pop())) {
        newHdrs.set('Access-Control-Allow-Origin', '*');
    }
    newHdrs.set('cache-control', 'public, max-age=31536000');
    removeHeaders.forEach((header) => {
        newHdrs.delete(header);
    });

    if (response.status > 399) {
        return new Response(response.statusText, {
            status: response.status
        })
    }

    response = new Response(response.body, {
        status: response.status,
        statusText: response.statusText,
        headers: newHdrs
    });
    event.waitUntil(cache.put(url, response.clone()))
    return response;
}
New paste