Skip to content

Built for people who want to own their automations. Join the waitlist for an invite.

Package listing

@kody/airtable

src/get-table.ts

63 lines · 1.9 KB · TypeScript
import { pickAuthInput } from './auth.ts'
import { listTables } from './list-tables.ts'
import type { AirtableAuthInput, AirtableTableSummary } from './types.ts'
import { optionalString, requireRecord, requireString } from './types.ts'

export type GetTableInput = AirtableAuthInput & {
	/** Base id (`app…`). */
	baseId: string
	/** Table id (`tbl…`). */
	tableId?: string
	/** Table name. Used when `tableId` is omitted. */
	tableName?: string
}

/**
 * Get one table from an Airtable base schema. Needs `schema.bases:read`.
 * @example
 * import getTable from 'kody:@kody/airtable/get-table'
 * const table = await getTable({
 *   baseId: 'appXXXXXXXXXXXXXX',
 *   tableId: 'tblXXXXXXXXXXXXXX',
 * })
 */
export async function getTable(input: GetTableInput): Promise<AirtableTableSummary> {
	const tableId = optionalString(input.tableId, 'tableId')
	const tableName = optionalString(input.tableName, 'tableName')
	if (!tableId && !tableName) {
		throw new Error('get-table requires tableId or tableName.')
	}
	const { items } = await listTables(input)
	const match = items.find((item) => {
		if (tableId && item.id === tableId) return true
		if (tableName && item.name === tableName) return true
		return false
	})
	if (!match) {
		throw new Error(
			`Airtable table not found in base ${requireString(input.baseId, 'baseId')}: ${tableId ?? tableName}.`,
		)
	}
	return match
}

/**
 * Get one table from an Airtable base schema.
 * @example
 * import getTable from 'kody:@kody/airtable/get-table'
 * const table = await getTable({
 *   baseId: 'appXXXXXXXXXXXXXX',
 *   tableName: 'Tasks',
 * })
 */
export default async function getTableEntrypoint(
	params: Partial<GetTableInput> & Record<string, unknown> = {},
) {
	const input = requireRecord(params, 'get-table')
	return getTable({
		baseId: requireString(input.baseId, 'baseId'),
		tableId: optionalString(input.tableId, 'tableId'),
		tableName: optionalString(input.tableName, 'tableName'),
		...pickAuthInput(input),
	})
}