Edits history of script submission #12501 for ' Upload Image From File (klaviyo)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    type Klaviyo = {
      apiKey: string;
    };
    type Base64 = string;
    /**
     * Upload Image From File
     * Upload an image from a file.
    
    If you want to import an image from an existing url or a data uri, use the Upload Image From URL endpoint instead.*Rate limits*:Burst: `3/s`Steady: `100/m`Daily: `100/d`
    
     */
    export async function main(
      auth: Klaviyo,
      revision: string,
      body: {
        file: {
          base64: Base64;
          type:
            | "image/png"
            | "image/jpeg"
            | "image/gif"
            | "application/pdf"
            | "appication/json"
            | "text/csv"
            | "text/plain"
            | "audio/mpeg"
            | "audio/wav"
            | "video/mp4";
          name: string;
        };
        name?: string;
        hidden?: false | true;
      },
    ) {
      const url = new URL(`https://a.klaviyo.com/api/image-upload`);
    
      const formData = new FormData();
      for (const [k, v] of Object.entries(body)) {
        if (v !== undefined && v !== "") {
          if (["file"].includes(k)) {
            const { base64, type, name } = v as {
              base64: Base64;
              type: string;
              name: string;
            };
            formData.append(
              k,
              new Blob([Uint8Array.from(atob(base64), (m) => m.codePointAt(0)!)], {
                type,
              }),
              name,
            );
          } else {
            formData.append(k, String(v));
          }
        }
      }
      const response = await fetch(url, {
        method: "POST",
        headers: {
          revision: revision,
          "Accept": "application/vnd.api+json",
          Authorization: "Klaviyo-API-Key " + auth.apiKey,
        },
        body: formData,
      });
      if (!response.ok) {
        const text = await response.text();
        throw new Error(`${response.status} ${text}`);
      }
      return await response.json();
    }
    

    Submitted by hugo697 428 days ago