-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostgres.js
More file actions
37 lines (29 loc) · 763 Bytes
/
Copy pathpostgres.js
File metadata and controls
37 lines (29 loc) · 763 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
const { createClient, createPool } = require('@vercel/postgres');
let dbPromise = null;
async function getDb() {
if (!dbPromise) {
dbPromise = initializeDb();
}
return dbPromise;
}
async function initializeDb() {
const connectionString = process.env.POSTGRES_URL;
if (!connectionString) {
throw new Error('POSTGRES_URL is not configured');
}
try {
return createPool({ connectionString });
} catch (error) {
if (error.code !== 'invalid_connection_string') {
throw error;
}
const client = createClient({ connectionString });
await client.connect();
return client;
}
}
async function sql(strings, ...values) {
const db = await getDb();
return db.sql(strings, ...values);
}
module.exports = { sql };