0

Get a connection URI

by
Published Apr 8, 2025

Retrieves a connection URI for the specified database. You can obtain a `project_id` by listing the projects for your Neon account. You can obtain the `database_name` by listing the databases for a branch. You can obtain a `role_name` by listing the roles for a branch.

Script neondb Verified

The script

Submitted by hugo697 Bun
Verified 428 days ago
1
//native
2
type Neondb = {
3
	apiKey: string
4
}
5
/**
6
 * Get a connection URI
7
 * Retrieves a connection URI for the specified database.
8
You can obtain a `project_id` by listing the projects for your Neon account.
9
You can obtain the `database_name` by listing the databases for a branch.
10
You can obtain a `role_name` by listing the roles for a branch.
11

12
 */
13
export async function main(
14
	auth: Neondb,
15
	project_id: string,
16
	branch_id: string | undefined,
17
	endpoint_id: string | undefined,
18
	database_name: string | undefined,
19
	role_name: string | undefined,
20
	pooled: string | undefined
21
) {
22
	const url = new URL(`https://console.neon.tech/api/v2/projects/${project_id}/connection_uri`)
23
	for (const [k, v] of [
24
		['branch_id', branch_id],
25
		['endpoint_id', endpoint_id],
26
		['database_name', database_name],
27
		['role_name', role_name],
28
		['pooled', pooled]
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