import { CacheOverride } from "fastly:cache-override";

addEventListener("fetch", event => {
  // Get the request from the client.
  const req = event.request;
  const url = new URL(req.url);
  let path = url.pathname.split("/");
 
  const pathPrefixes = [];

  // Extract all possible prefixes of the URL path
  while (path.length) {
    pathPrefixes.push(path.join("/"));
    path.pop();
  }
  console.log(pathPrefixes.join(" "));

  // Join the path prefixes into a valid surrogate key cache override
  const cacheOverride = new CacheOverride('override', {
    surrogateKey: pathPrefixes.join(" ")
  });

  // Send the request to `origin_0`.
  const backendResponse = fetch(req, {
    backend: "origin_0",
    cacheOverride
  });

  // Send the backend response back to the client.
  event.respondWith(backendResponse);
});