-
-
Notifications
You must be signed in to change notification settings - Fork 144
/
db.js
41 lines (33 loc) · 895 Bytes
/
db.js
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
const EventEmitter = require('events')
const pg = require('pg')
class Db extends EventEmitter {
constructor (config) {
super()
config.application_name = config.application_name || 'pgboss'
this.config = config
}
async open () {
this.pool = new pg.Pool(this.config)
this.pool.on('error', error => this.emit('error', error))
this.opened = true
}
async close () {
if (!this.pool.ending) {
this.opened = false
await this.pool.end()
}
}
async executeSql (text, values) {
if (this.opened) {
return await this.pool.query(text, values)
}
}
static quotePostgresStr (str) {
const delimeter = '$sanitize$'
if (str.includes(delimeter)) {
throw new Error(`Attempted to quote string that contains reserved Postgres delimeter: ${str}`)
}
return `${delimeter}${str}${delimeter}`
}
}
module.exports = Db