0

Insert record

by
Published Apr 8, 2025

Insert a new Record into the Table

Script xata Verified

The script

Submitted by hugo697 Bun
Verified 428 days ago
1
//native
2
type Xata = {
3
	apiKey: string
4
	workspaceUrl: string
5
}
6
/**
7
 * Insert record
8
 * Insert a new Record into the Table
9
 */
10
export async function main(
11
	auth: Xata,
12
	db_branch_name: string,
13
	table_name: string,
14
	columns: string | undefined,
15
	body: {}
16
) {
17
	const url = new URL(`${auth.workspaceUrl}/db/${db_branch_name}/tables/${table_name}/data`)
18
	for (const [k, v] of [['columns', columns]]) {
19
		if (v !== undefined && v !== '' && k !== undefined) {
20
			url.searchParams.append(k, v)
21
		}
22
	}
23
	const response = await fetch(url, {
24
		method: 'POST',
25
		headers: {
26
			'Content-Type': 'application/json',
27
			Authorization: 'Bearer ' + auth.apiKey
28
		},
29
		body: JSON.stringify(body)
30
	})
31
	if (!response.ok) {
32
		const text = await response.text()
33
		throw new Error(`${response.status} ${text}`)
34
	}
35
	return await response.json()
36
}
37