import { createClient } from "edgedb";
type EdgeDB = {
dsn?: string;
password?: string;
secretKey?: string;
host?: string;
port?: number;
user?: string;
database?: string;
instanceName?: string;
}
export async function main(
edgedb: EdgeDB,
query: string = 'select "Hello, EdgeDB!"'
) {
validateEdgedb(edgedb);
const filteredConnectionDetails = Object.fromEntries(
Object.entries(edgedb).filter(([key, value]) => value)
);
const client = createClient(filteredConnectionDetails);
const results = await client.query(query);
return results;
}
function validateEdgedb(edgedb: EdgeDB) {
if ('dsn' in edgedb) {
if (!('password' in edgedb) && !('secretKey' in edgedb)) {
throw new Error('When dsn is set, either password or secretKey is required.');
}
}
else { // dsn not set
// Check for host, port, user, and database all set
if ('host' in edgedb && 'port' in edgedb && 'user' in edgedb && 'database' in edgedb) {
if (!('password' in edgedb) && !('secretKey' in edgedb)) {
throw new Error('With host, port, user, and database set, either password or secretKey is required.');
}
}
else if ('instanceName' in edgedb && 'secretKey' in edgedb) {
// These properties are set, so this condition is satisfied
}
// Neither sets of properties are satisfied, throw an error
else {
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.');
}
}
}
Submitted by devon356 464 days ago