0

Upsert record with ID

by
Published Apr 8, 2025
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
 * Upsert record with ID
8
 *
9
 */
10
export async function main(
11
	auth: Xata,
12
	db_branch_name: string,
13
	table_name: string,
14
	record_id: string,
15
	columns: string | undefined,
16
	ifVersion: string | undefined,
17
	body: {}
18
) {
19
	const url = new URL(
20
		`${auth.workspaceUrl}/db/${db_branch_name}/tables/${table_name}/data/${record_id}`
21
	)
22
	for (const [k, v] of [
23
		['columns', columns],
24
		['ifVersion', ifVersion]
25
	]) {
26
		if (v !== undefined && v !== '' && k !== undefined) {
27
			url.searchParams.append(k, v)
28
		}
29
	}
30
	const response = await fetch(url, {
31
		method: 'POST',
32
		headers: {
33
			'Content-Type': 'application/json',
34
			Authorization: 'Bearer ' + auth.apiKey
35
		},
36
		body: JSON.stringify(body)
37
	})
38
	if (!response.ok) {
39
		const text = await response.text()
40
		throw new Error(`${response.status} ${text}`)
41
	}
42
	return await response.json()
43
}
44