0
Query an EdgeDB database
One script reply has been approved by the moderators Verified

Query an EdgeDB database, hosted on EdgeDB Cloud or self-hosted

Created by devon356 219 days ago Viewed 4278 times
0
Submitted by devon356 Bun
Verified 219 days ago
1
import { createClient } from "edgedb";
2

3
type EdgeDB = {
4
  dsn?: string;
5
  password?: string;
6
  secretKey?: string;
7
  host?: string;
8
  port?: number;
9
  user?: string;
10
  database?: string;
11
  instanceName?: string;
12
}
13

14
export async function main(
15
  edgedb: EdgeDB,
16
  query: string = 'select "Hello, EdgeDB!"'
17
) {
18
validateEdgedb(edgedb);
19
const filteredConnectionDetails = Object.fromEntries(
20
  Object.entries(edgedb).filter(([key, value]) => value)
21
);
22
  const client = createClient(filteredConnectionDetails);
23
  const results = await client.query(query);
24
  return results;
25
}
26

27
function validateEdgedb(edgedb: EdgeDB) {
28
  if ('dsn' in edgedb) {
29
    if (!('password' in edgedb) && !('secretKey' in edgedb)) {
30
      throw new Error('When dsn is set, either password or secretKey is required.');
31
    }
32
  } 
33
  else { // dsn not set
34
    // Check for host, port, user, and database all set
35
    if ('host' in edgedb && 'port' in edgedb && 'user' in edgedb && 'database' in edgedb) {
36
      if (!('password' in edgedb) && !('secretKey' in edgedb)) {
37
        throw new Error('With host, port, user, and database set, either password or secretKey is required.');
38
      }
39
    } 
40
    else if ('instanceName' in edgedb && 'secretKey' in edgedb) {
41
      // These properties are set, so this condition is satisfied
42
    } 
43
    // Neither sets of properties are satisfied, throw an error
44
    else {
45
      throw new Error('If dsn is not set, either host, port, user, database and (password or secretKey) must all be set or both instanceName and secretKey must be set.');
46
    }
47
  }
48
}