Edits history of script submission #22331 for ' List Records (airtable)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    type Airtable = {
      apiKey: string;
    };
    
    type AirtableTable = {
      baseId: string;
      tableName: string;
    };
    
    /**
     * List Records
     * List records in a table, following Airtable's `offset` pagination to return
     * every record (the API returns at most 100 per page). Optionally cap the
     * number of records returned with `maxRecords`.
     */
    export async function main(
      atCon: Airtable,
      atTable: AirtableTable,
      maxRecords?: number,
    ) {
      const records: any[] = [];
      let offset: string | undefined = undefined;
    
      do {
        const url = new URL(
          `https://api.airtable.com/v0/${atTable.baseId}/${encodeURIComponent(
            atTable.tableName,
          )}`,
        );
        if (offset !== undefined) {
          url.searchParams.append("offset", offset);
        }
    
        const response = await fetch(url, {
          method: "GET",
          headers: {
            Authorization: `Bearer ${atCon.apiKey}`,
          },
        });
    
        if (!response.ok) {
          throw new Error(`${response.status} ${await response.text()}`);
        }
    
        const page = await response.json();
        records.push(...(page.records ?? []));
        offset = page.offset;
      } while (
        offset !== undefined &&
        (maxRecords === undefined || records.length < maxRecords)
      );
    
      return {
        records:
          maxRecords !== undefined ? records.slice(0, maxRecords) : records,
      };
    }
    

    Submitted by hugo989 20 days ago