Edits history of script submission #22442 for ' Create Campaign (mailchimp)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Find more information about the parameters at
     * https://mailchimp.com/developer/marketing/api/campaigns/add-campaign/
     */
    type Mailchimp = {
      api_key: string;
      server: string;
    };
    export async function main(
      auth: Mailchimp,
      type: "regular" | "plaintext" | "rss" | "variate",
      content_type: "template" | "multichannel" = "template",
      rss_opts?: Record<string, any>,
      recipients?: Record<string, any>,
      variate_settings?: Record<string, any>,
      settings?: Record<string, any>,
      tracking?: Record<string, any>,
      social_card?: Record<string, any>,
    ) {
      const url = `https://${auth.server}.api.mailchimp.com/3.0/campaigns`;
      const body = {
        type,
        content_type,
        rss_opts,
        recipients,
        variate_settings,
        settings,
        tracking,
        social_card,
      };
    
      const response = await fetch(url, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${auth.api_key}`,
        },
        body: JSON.stringify(removeObjectEmptyFields(body)),
      });
    
      if (!response.ok) {
        throw Error(await response.text());
      }
      return await response.json();
    }
    
    function removeObjectEmptyFields(
      object?: Record<string, any>,
      removeEmptyArraysAndObjects = true,
      createNewObject = true,
    ) {
      if (!object || typeof object !== "object") return {}
      const obj = createNewObject ? { ...object } : object
      const emptyValues = [undefined, null, ""]
      for (const key in obj) {
        const value = obj[key]
        if (emptyValues.includes(value)) {
          delete obj[key]
        } else if (typeof value === "object") {
          if (Object.keys(value).length) {
            obj[key] = removeObjectEmptyFields(value, removeEmptyArraysAndObjects, false)
          }
          if (!Object.keys(value).length && removeEmptyArraysAndObjects) {
            delete obj[key]
          }
        }
      }
      return obj
    }
    

    Submitted by hugo989 6 days ago