1 | |
2 |
|
3 | export type DynSelect_base_id = string |
4 |
|
5 | |
6 | export async function base_id(auth: RT.Airtable) { |
7 | const options: { value: string; label: string }[] = [] |
8 | let offset: string | undefined = undefined |
9 | do { |
10 | const url = new URL("https://api.airtable.com/v0/meta/bases") |
11 | if (offset) { |
12 | url.searchParams.append("offset", offset) |
13 | } |
14 | const response = await fetch(url, { |
15 | headers: { |
16 | Authorization: `Bearer ${auth.apiKey}`, |
17 | Accept: "application/json", |
18 | }, |
19 | }) |
20 | if (!response.ok) { |
21 | throw new Error(`${response.status} ${await response.text()}`) |
22 | } |
23 | const page = (await response.json()) as { |
24 | bases: { id: string; name: string }[] |
25 | offset?: string |
26 | } |
27 | options.push(...page.bases.map((b) => ({ value: b.id, label: b.name }))) |
28 | offset = page.offset |
29 | } while (offset) |
30 | return options |
31 | } |
32 |
|
33 | |
34 | * Create Table |
35 | * 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. |
36 | */ |
37 | export async function main( |
38 | auth: RT.Airtable, |
39 | base_id: DynSelect_base_id, |
40 | name: string, |
41 | fields: { |
42 | name: string |
43 | type: string |
44 | description?: string |
45 | options?: { [key: string]: any } |
46 | }[], |
47 | description: string | undefined |
48 | ) { |
49 | const body: { [key: string]: any } = { name, fields } |
50 | if (description != null && description !== "") { |
51 | body.description = description |
52 | } |
53 |
|
54 | const response = await fetch( |
55 | `https://api.airtable.com/v0/meta/bases/${base_id}/tables`, |
56 | { |
57 | method: "POST", |
58 | headers: { |
59 | Authorization: `Bearer ${auth.apiKey}`, |
60 | "Content-Type": "application/json", |
61 | Accept: "application/json", |
62 | }, |
63 | body: JSON.stringify(body), |
64 | } |
65 | ) |
66 | if (!response.ok) { |
67 | throw new Error(`${response.status} ${await response.text()}`) |
68 | } |
69 |
|
70 | return await response.json() |
71 | } |
72 |
|