Edits history of script submission #11283 for ' Get catalogs items (pinterest)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    type Pinterest = {
      token: string;
    };
    /**
     * Get catalogs items
     * Get the items of the catalog owned by the "operation user_account".
     */
    export async function main(
      auth: Pinterest,
      ad_account_id: string | undefined,
      country: string | undefined,
      language: string | undefined,
      item_ids: string | undefined,
      filters: any,
    ) {
      const url = new URL(`https://api.pinterest.com/v5/catalogs/items`);
      for (const [k, v] of [
        ["ad_account_id", ad_account_id],
        ["country", country],
        ["language", language],
        ["item_ids", item_ids],
      ]) {
        if (v !== undefined && v !== "" && k !== undefined) {
          url.searchParams.append(k, v);
        }
      }
      encodeParams({ filters }).forEach((v, k) => {
        if (v !== undefined && v !== "") {
          url.searchParams.append(k, v);
        }
      });
      const response = await fetch(url, {
        method: "GET",
        headers: {
          Authorization: "Bearer " + auth.token,
        },
        body: undefined,
      });
      if (!response.ok) {
        const text = await response.text();
        throw new Error(`${response.status} ${text}`);
      }
      return await response.json();
    }
    
    function encodeParams(o: any) {
      function iter(o: any, path: string) {
        if (Array.isArray(o)) {
          o.forEach(function (a) {
            iter(a, path + "[]");
          });
          return;
        }
        if (o !== null && typeof o === "object") {
          Object.keys(o).forEach(function (k) {
            iter(o[k], path + "[" + k + "]");
          });
          return;
        }
        data.push(path + "=" + o);
      }
      const data: string[] = [];
      Object.keys(o).forEach(function (k) {
        if (o[k] !== undefined) {
          iter(o[k], k);
        }
      });
      return new URLSearchParams(data.join("&"));
    }
    

    Submitted by hugo697 537 days ago