0

Read records from a grist table

by
Published Jul 22, 2024

https://support.getgrist.com/api/#tag/records/operation/listRecords

Script grist
  • Submitted by manu [tennox]332 Bun
    Created 687 days ago
    1
    import { mapValues } from 'lodash-es'
    2
    
    
    3
    // https://hub.windmill.dev/resource_types/155/grist
    4
    type Grist = {
    5
      token: string,
    6
      teamOrBaseURL: string
    7
    }
    8
    // https://hub.windmill.dev/resource_types/156/grist_document
    9
    type GristDoc = {
    10
      doc: string,
    11
      gristInstance: Grist
    12
    }
    13
    
    
    14
    export async function main(
    15
      gristDoc: GristDoc,
    16
      table: string,
    17
      params?: { filter?: Object, sort?: string, limit?: number, hidden?: boolean },
    18
    ): Promise<any> {
    19
      const { gristInstance: grist, doc } = gristDoc
    20
    
    
    21
      // DOCS: https://support.getgrist.com/api/#tag/records/operation/listRecords
    22
      const baseURL = grist.teamOrBaseURL.includes('.') ? grist.teamOrBaseURL : `https://${grist.teamOrBaseURL}.getgrist.com`
    23
      let paramsString = ''
    24
      if (params) {
    25
        const encodedParams = new URLSearchParams(mapValues(params, v => typeof v === 'string' ? v : JSON.stringify(v))).toString()
    26
        paramsString = `?${encodedParams}`
    27
      }
    28
      console.log(paramsString)
    29
      const response = await fetch(
    30
        `${baseURL}/api/docs/${doc}/tables/${table}/records`
    31
        + paramsString,
    32
        {
    33
          method: 'GET',
    34
          headers: {
    35
            'Authorization': `Bearer ${grist.token}`,
    36
            'Content-Type': 'application/json'
    37
          },
    38
        });
    39
    
    
    40
      if (!response.ok) {
    41
        throw new Error(`Failed to write to Grist table: ${response.statusText} ${JSON.stringify(await response.json())}`);
    42
      }
    43
    
    
    44
      return await response.json();
    45
    }
    46