0

Get a formatted generic connection string for a cluster

by
Published Oct 17, 2025

Can be used by the following roles assigned at the organization, folder or cluster scope: - ORG_ADMIN - CLUSTER_ADMIN - CLUSTER_OPERATOR_WRITER - CLUSTER_DEVELOPER - FOLDER_ADMIN - FOLDER_MOVER

Script cockroachdb Verified

The script

Submitted by hugo697 Bun
Verified 235 days ago
1
//native
2
type Cockroachdb = {
3
  token: string;
4
};
5
/**
6
 * Get a formatted generic connection string for a cluster
7
 * Can be used by the following roles assigned at the organization, folder or cluster scope:
8
- ORG_ADMIN
9
- CLUSTER_ADMIN
10
- CLUSTER_OPERATOR_WRITER
11
- CLUSTER_DEVELOPER
12
- FOLDER_ADMIN
13
- FOLDER_MOVER
14

15
 */
16
export async function main(
17
  auth: Cockroachdb,
18
  cluster_id: string,
19
  database: string | undefined,
20
  sql_user: string | undefined,
21
  os: "MAC" | "LINUX" | "WINDOWS" | undefined,
22
) {
23
  const url = new URL(
24
    `https://cockroachlabs.cloud/api/v1/clusters/${cluster_id}/connection-string`,
25
  );
26
  for (const [k, v] of [
27
    ["database", database],
28
    ["sql_user", sql_user],
29
    ["os", os],
30
  ]) {
31
    if (v !== undefined && v !== "" && k !== undefined) {
32
      url.searchParams.append(k, v);
33
    }
34
  }
35
  const response = await fetch(url, {
36
    method: "GET",
37
    headers: {
38
      Authorization: "Bearer " + auth.token,
39
    },
40
    body: undefined,
41
  });
42
  if (!response.ok) {
43
    const text = await response.text();
44
    throw new Error(`${response.status} ${text}`);
45
  }
46
  return await response.json();
47
}
48