0

Resolve a Git Branch to a Xata branch

by
Published Apr 8, 2025

In order to resolve the database branch, the following algorithm is used: * if the `gitBranch` was provided and is found in the git branches mapping, the associated Xata branch is returned * else, if a Xata branch with the exact same name as `gitBranch` exists, return it * else, if `fallbackBranch` is provided and a branch with that name exists, return it * else, return the default branch of the DB (`main` or the first branch) Example call: ```json // GET https://tutorial-ng7s8c.

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
 * Resolve a Git Branch to a Xata branch
8
 * In order to resolve the database branch, the following algorithm is used:
9
* if the `gitBranch` was provided and is found in the git branches mapping, the associated Xata branch is returned
10
* else, if a Xata branch with the exact same name as `gitBranch` exists, return it
11
* else, if `fallbackBranch` is provided and a branch with that name exists, return it
12
* else, return the default branch of the DB (`main` or the first branch)
13

14
Example call:
15

16
```json
17
// GET https://tutorial-ng7s8c.
18
 */
19
export async function main(
20
	auth: Xata,
21
	db_name: string,
22
	gitBranch: string | undefined,
23
	fallbackBranch: string | undefined
24
) {
25
	const url = new URL(`${auth.workspaceUrl}/dbs/${db_name}/resolveBranch`)
26
	for (const [k, v] of [
27
		['gitBranch', gitBranch],
28
		['fallbackBranch', fallbackBranch]
29
	]) {
30
		if (v !== undefined && v !== '' && k !== undefined) {
31
			url.searchParams.append(k, v)
32
		}
33
	}
34
	const response = await fetch(url, {
35
		method: 'GET',
36
		headers: {
37
			Authorization: 'Bearer ' + auth.apiKey
38
		},
39
		body: undefined
40
	})
41
	if (!response.ok) {
42
		const text = await response.text()
43
		throw new Error(`${response.status} ${text}`)
44
	}
45
	return await response.json()
46
}
47