Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

1.2 KB
Raw Blame
import { z } from "zod";
import { RESIZABLE_IMAGE_MIME_TYPES } from "@webstudio-is/sdk";

const urlBody = z.object({
  url: z.string(),
});

export const getBrowserUploadBody = async (
  request: Request,
  contentType: string | null
) => {
  const body = request.body;
  if (body === null) {
    throw new Error("Asset body is empty");
  }

  if (request.headers.get("x-webstudio-asset-source") !== "url") {
    return body;
  }
  if (contentType?.includes("application/json") !== true) {
    throw new Error("Invalid URL asset upload content type");
  }

  const urlParse = urlBody.safeParse(await request.json());
  if (urlParse.success === false) {
    throw new Error("Invalid URL asset upload body");
  }

  const { url } = urlParse.data;
  const imageRequest = await fetch(url, {
    method: "GET",
    headers: {
      Accept: RESIZABLE_IMAGE_MIME_TYPES.join(","),
    },
  });

  if (imageRequest.ok === false) {
    const error = await imageRequest.text();
    throw new Error(
      `An error occurred while fetching the image at ${url}: ${error.slice(0, 500)}`
    );
  }

  if (imageRequest.body === null) {
    throw new Error(
      `An error occurred while fetching the image at ${url}: Image body is null`
    );
  }
  return imageRequest.body;
};