import { encodeUrl } from "@borderless/base64";

// Fastly only supports URL size up to 8K
// Base64 encoding will increase the body size by 30% and
// we want to leave some buffer, so set the limit to 4K
const MAX_BODY_CONVERT_SIZE = 4 * 1024;

async function handler(event) {
  // Get the request from the client.
  let req = event.request;

  // If this is a POST request...
  if (req.method === "POST") {
    // Get the body of the request.
    let body = await req.arrayBuffer();

    if (body.byteLength < MAX_BODY_CONVERT_SIZE && body.byteLength > 1) {
      console.log("Converting POST body to base64 query param...");

      // Encode the body as base64.
      const encoded = encodeUrl(body);

      // Construct a new URL with the encoded body as a query parameter.
      const url = new URL(req.url);
      url.searchParams.set("postdata", encoded);

      console.log("GET request URL is " + url);

      // Replace the original request with a GET request to the new URL.
      return fetch(
        new Request(url.toString(), {
          method: "GET",
          headers: req.headers
        }),
        {
          backend: "origin_0"
        }
      );
    }
  }

  // Otherwise, forward the request to the origin.
  return fetch(req, {
    backend: "origin_0"
  });
}

addEventListener("fetch", (event) => event.respondWith(handler(event)));