Confused about how worker functions w/ fetch calls...
# workers-help
s
Typing up code...
Copy code
javascript
addEventListener("fetch", event => {
  console.log('start')
  // If this request is coming from image resizing worker,
  // avoid causing an infinite loop by resizing it again.
  // In other words, this worker tries to fetch the source image from
  // the website, but this worker gets called again instead.
  if (/auto-image/.test(event.request.headers.get("via"))) {
    console.log('matched via header: ', event.request.headers.get('via'))
    return fetch(event.request)
  }
  if (/imagedelivery.net/.test(event.request.headers.get("cf-worker"))) {
    console.log('matched cf-worker header: ', event.request.headers.get('cf-worker'))
    return
    // return fetch(event.request)
  }

  // Now you can safely use image resizing here
  event.passThroughOnException();
  console.log('respondWith about to be called')
  event.respondWith(handleRequest(event.request))
});
in my
handleRequest
, i'm issuing a fetch request to Cloudflare Images to perform manipulations on an image. if the image doesn't exist in my account (i get a 404), i upload the image and then re-do the first fetch
this all works fine if the image already exists
the thing i'm mostly confused about is that when the image doesnt exist and needs to get uploaded, the
console.log('matched cf-worker header'...
runs. as in, it's the very first thing to get called other than
console.log('start')
shouldn't the very first request NOT be that? my thought was that that particular
if
statement might run when i'm doing the CF Images API requests later on in the worker
so basically right now, if an image doesnt exist, my worker runs twice. the first time it runs, it hits the
imagedelivery.net
header check. then it runs again doing the
event.respondWith...
i assume im misunderstanding something, because that
via
header check never seems to run, but i thought i was getting infinite loops before adding that
actually maybe this makes sense... i'm still awaiting in the first request so that's why it happens twice / the order is mixed up