-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.ts
41 lines (37 loc) · 1.02 KB
/
db.ts
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
38
39
40
41
import { Client, QueryResult } from "pg";
import { loadEnvConfig } from "@next/env";
const projectDir = process.cwd();
loadEnvConfig(projectDir);
// loadEnvConfig(process.cwd());
// helper function
export async function getClient(): Promise<Client> {
// PRODUCTION
if (process.env.POSTGRES_URL) {
const client = new Client({
connectionString: process.env.POSTGRES_URL + "?sslmode=require",
});
return client;
}
// DEVELOPMENT
const client = new Client({
user: process.env.POSTGRES_USER,
host: process.env.POSTGRES_HOST,
database: process.env.POSTGRES_NAME,
password: process.env.POSTGRES_PASSWORD,
port: parseInt(process.env.POSTGRES_PORT!),
});
return client;
}
// UTILITY FUNCTION - dynamic db query helper to streamline the db connection
export async function sql(
sql: string,
values?: Array<any>
): Promise<QueryResult<any>> {
const client = await getClient();
//
await client.connect();
const res = await client.query(sql, values);
await client.end();
//
return res;
}