Edits history of script submission #12881 for ' List all API keys (persona)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    type Persona = {
      apiKey: string;
    };
    /**
     * List all API keys
     * Returns a list of your organization's API keys.
     */
    export async function main(
      auth: Persona,
      page: any,
      fields: string | undefined,
      filter: any,
      Key_Inflection?: string,
      Idempotency_Key?: string,
      Persona_Version?: string,
    ) {
      const url = new URL(`https://api.withpersona.com/api/v1/api-keys`);
      for (const [k, v] of [["fields", fields]]) {
        if (v !== undefined && v !== "" && k !== undefined) {
          url.searchParams.append(k, v);
        }
      }
      encodeParams({ page, filter }).forEach((v, k) => {
        if (v !== undefined && v !== "") {
          url.searchParams.append(k, v);
        }
      });
      const headers: Record<string, string> = {
        Authorization: `Bearer ${auth.apiKey}`,
      };
      if (Key_Inflection) {
        headers["Key-Inflection"] = Key_Inflection;
      }
      if (Idempotency_Key) {
        headers["Idempotency-Key"] = Idempotency_Key;
      }
      if (Persona_Version) {
        headers["Persona-Version"] = Persona_Version;
      }
      const response = await fetch(url, {
        method: "GET",
        headers,
        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 428 days ago