-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpostgres.ts
47 lines (38 loc) · 1.34 KB
/
postgres.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
42
43
44
45
46
47
import { Pool, PoolConfig, QueryResult } from 'pg'
import { LogFunction } from './log'
export default class PostgresHandler {
public connect: Promise<void>
public connectResolve?: () => void
public client: Pool
public connected: boolean
public log: (message: string) => void
constructor (postgresConfig: PoolConfig, log?: LogFunction) {
this.connect = new Promise((resolve) => this.connectResolve = resolve)
this.connected = false
this.log = (content) => {
if (log) log(content, 'postgres')
}
this.client = new Pool(postgresConfig)
this.client.on("connect", () => {
if (!this.connected) {
this.connected = true
this.log("Connected.")
if (this.connectResolve) this.connectResolve()
}
})
this.client.connect()
}
/**
* Query the POSTGRES database
*/
query (query: string, ...args: unknown[]): Promise<QueryResult> {
return new Promise((resolve, reject) => {
// const startAt = Date.now();
this.client.query(query, args, (error, results) => {
// this.log(`Query run in ${parseInt(Date.now() - startAt)}ms`);
if (error) reject(error)
else resolve(results)
})
})
}
}