|
| 1 | +import { DsqlSigner } from "@aws-sdk/dsql-signer"; |
| 2 | +import pg from "pg"; |
| 3 | +import assert from "node:assert"; |
| 4 | +const { Client } = pg; |
| 5 | + |
| 6 | +const ADMIN = "admin"; |
| 7 | +const NON_ADMIN_SCHEMA = "myschema"; |
| 8 | + |
| 9 | +async function getConnection(clusterEndpoint, user, region) { |
| 10 | + const signer = new DsqlSigner({ |
| 11 | + hostname: clusterEndpoint, |
| 12 | + region, |
| 13 | + }); |
| 14 | + let token; |
| 15 | + // Generate a fresh password token for each connection, to ensure the token is |
| 16 | + // not expired when the connection is established |
| 17 | + if (user === ADMIN) { |
| 18 | + token = await signer.getDbConnectAdminAuthToken(); |
| 19 | + } |
| 20 | + else { |
| 21 | + signer.user = user; |
| 22 | + token = await signer.getDbConnectAuthToken() |
| 23 | + } |
| 24 | + let client = new Client({ |
| 25 | + host: clusterEndpoint, |
| 26 | + user: user, |
| 27 | + password: token, |
| 28 | + database: "postgres", |
| 29 | + port: 5432, |
| 30 | + ssl: { |
| 31 | + rejectUnauthorized: true, |
| 32 | + } |
| 33 | + }); |
| 34 | + |
| 35 | + // Connect |
| 36 | + await client.connect(); |
| 37 | + console.log("Successfully opened connection"); |
| 38 | + return client; |
| 39 | +} |
| 40 | + |
| 41 | +async function example() { |
| 42 | + |
| 43 | + const clusterEndpoint = process.env.CLUSTER_ENDPOINT; |
| 44 | + assert(clusterEndpoint); |
| 45 | + const user = process.env.CLUSTER_USER; |
| 46 | + assert(user); |
| 47 | + const region = process.env.REGION; |
| 48 | + assert(region); |
| 49 | + |
| 50 | + let client; |
| 51 | + try { |
| 52 | + client = await getConnection(clusterEndpoint, user, region); |
| 53 | + |
| 54 | + if (user !== ADMIN) { |
| 55 | + await client.query("SET search_path=" + NON_ADMIN_SCHEMA) |
| 56 | + } |
| 57 | + |
| 58 | + // Create a new table |
| 59 | + await client.query(`CREATE TABLE IF NOT EXISTS owner ( |
| 60 | + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), |
| 61 | + name VARCHAR(30) NOT NULL, |
| 62 | + city VARCHAR(80) NOT NULL, |
| 63 | + telephone VARCHAR(20) |
| 64 | + )`); |
| 65 | + |
| 66 | + // Insert some data |
| 67 | + await client.query("INSERT INTO owner(name, city, telephone) VALUES($1, $2, $3)", |
| 68 | + ["John Doe", "Anytown", "555-555-1900"] |
| 69 | + ); |
| 70 | + |
| 71 | + // Check that data is inserted by reading it back |
| 72 | + const result = await client.query("SELECT id, city FROM owner where name='John Doe'"); |
| 73 | + assert.deepEqual(result.rows[0].city, "Anytown") |
| 74 | + assert.notEqual(result.rows[0].id, null) |
| 75 | + |
| 76 | + await client.query("DELETE FROM owner where name='John Doe'"); |
| 77 | + |
| 78 | + } catch (error) { |
| 79 | + console.error(error); |
| 80 | + throw error; |
| 81 | + } finally { |
| 82 | + client?.end() |
| 83 | + } |
| 84 | +} |
| 85 | + |
| 86 | +export { example } |
0 commit comments