Edits history of script submission #23486 for ' Create Table (airtable)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    export type DynSelect_base_id = string
    
    // Dropdown of the bases the token can access.
    export async function base_id(auth: RT.Airtable) {
      const options: { value: string; label: string }[] = []
      let offset: string | undefined = undefined
      do {
        const url = new URL("https://api.airtable.com/v0/meta/bases")
        if (offset) {
          url.searchParams.append("offset", offset)
        }
        const response = await fetch(url, {
          headers: {
            Authorization: `Bearer ${auth.apiKey}`,
            Accept: "application/json",
          },
        })
        if (!response.ok) {
          throw new Error(`${response.status} ${await response.text()}`)
        }
        const page = (await response.json()) as {
          bases: { id: string; name: string }[]
          offset?: string
        }
        options.push(...page.bases.map((b) => ({ value: b.id, label: b.name })))
        offset = page.offset
      } while (offset)
      return options
    }
    
    /**
     * Create Table
     * Create a table in a base. The first field becomes the primary field and must be a type Airtable allows as primary (e.g. singleLineText). Requires the schema.bases:write scope.
     */
    export async function main(
      auth: RT.Airtable,
      base_id: DynSelect_base_id,
      name: string,
      fields: {
        name: string
        type: string
        description?: string
        options?: { [key: string]: any }
      }[],
      description: string | undefined
    ) {
      const body: { [key: string]: any } = { name, fields }
      if (description != null && description !== "") {
        body.description = description
      }
    
      const response = await fetch(
        `https://api.airtable.com/v0/meta/bases/${base_id}/tables`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${auth.apiKey}`,
            "Content-Type": "application/json",
            Accept: "application/json",
          },
          body: JSON.stringify(body),
        }
      )
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      return await response.json()
    }
    

    Submitted by hugo989 3 hours ago