Skip to content

Instantly share code, notes, and snippets.

@nwoow
Created March 30, 2020 16:02
Show Gist options
  • Select an option

  • Save nwoow/8799d47c4c6de2286f9bc321de6a6c16 to your computer and use it in GitHub Desktop.

Select an option

Save nwoow/8799d47c4c6de2286f9bc321de6a6c16 to your computer and use it in GitHub Desktop.
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
/**
* Fetch and log a request
* @param {Request} request
*/
async function handleRequest(request) {
// Parse request URL to get access to query string
let url = new URL(request.url);
// Cloudflare-specific options are in the cf object.
let options = { cf: { image: {} } }
// Copy parameters from query string to request options.
// You can implement various different parameters here.
if (url.searchParams.has("fit")) options.cf.image.fit = url.searchParams.get("fit");
if (url.searchParams.has("width")) options.cf.image.width = url.searchParams.get("width");
if (url.searchParams.has("height")) options.cf.image.height = url.searchParams.get("height");
if (url.searchParams.has("quality")) options.cf.image.quality = url.searchParams.get("quality");
// Get URL of the original (full size) image to resize.
// You could adjust the URL here, e.g. prefix it with a fixed address of your server,
// so that user-visible URLs are shorter and cleaner.
const imageURL = url.searchParams.get("image");
// Build a request that passes through request headers,
// so that automatic format negotiation can work.
const imageRequest = new Request(imageURL, {
headers: request.headers,
});
// Returning fetch() with resizing options will pass through response with the resized image.
return fetch(imageRequest, options);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment