-
Notifications
You must be signed in to change notification settings - Fork 1
/
postgres.js
154 lines (135 loc) · 3.57 KB
/
postgres.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
/* @flow */
import { Pool } from 'pg'
import config from './config'
const { DATABASE } = config
let pool
function createPool(): Object {
if (!DATABASE) {
throw new Error(`No database config found`)
}
return new Pool({
host: DATABASE.HOST,
user: DATABASE.USER,
database: DATABASE.NAME,
password: DATABASE.PASSWORD,
port: DATABASE.PORT,
max: 20,
ssl: true,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000
})
}
export async function postQuery<T>(
text: string,
values: Array<string | number> = []
): Promise<Array<T>> {
pool = pool || createPool()
// $FlowFixMe
let client
try {
client = await pool.connect()
} catch (e) {
console.error('Could not connect to pool', e)
}
console.log(text, values)
let result
try {
result = await client.query(text, values)
} finally {
client.release()
}
console.log(result.rows)
return result.rows
}
export async function endPool(): Promise<void> {
if (pool) {
await pool.end()
pool = null
}
}
export async function postQuerySingle<T>(
text: string,
values: Array<string | number> = []
): Promise<T> {
let rows = await postQuery(text, values)
if (rows.length > 1) {
throw new Error(`Expected single result for query: ${text}, ${JSON.stringify(values)}`)
}
return rows[0]
}
export async function postInsert<T>(
table: string,
data: { [string]: string | number }
): Promise<T> {
let keys = Object.keys(data)
let values = keys.map(key => data[key])
let query = `
INSERT INTO ${table} (${keys.join(', ')})
VALUES (${keys.map((val, i) => `$${(i + 1).toString()}`).join(', ')})
RETURNING id;
`
return await postQuerySingle(query, values)
}
export async function postSelect<T>(
table: string,
criteria: { [string]: string },
columns: Array<string> = ['id'],
other: string
): Promise<Array<T>> {
let keys = Object.keys(criteria)
let values = keys.map(key => criteria[key])
let query = `
SELECT ${columns.join(', ')}
FROM ${table}
WHERE ${keys.map((key, i) => `${key} = $${i + 1}`).join(' AND ')}
`
if (other) {
query += other
}
query += ';'
return await postQuery(query, values)
}
export async function postSelectOne<T>(
table: string,
criteria: { [string]: string },
columns: Array<string> = ['id']
): Promise<T> {
let rows = await postSelect(table, criteria, columns)
if (rows.length > 1) {
throw new Error(`Expected single result for query: ${JSON.stringify(criteria)}`)
}
return rows[0]
}
export async function postSelectID<T>(
table: string,
id: string,
columns: Array<string> = ['id']
): Promise<T> {
return await postSelectOne(table, { id }, columns)
}
export async function postUpdateWhere<T>(
table: string,
criteria: { [string]: string },
data: { [string]: string }
): Promise<T> {
let keys = Object.keys(data)
let values = keys.map(key => data[key])
let criteriaKeys = Object.keys(criteria)
let criteriaValues = criteriaKeys.map(key => criteria[key])
let query = `
UPDATE ${table}
SET ${keys.map((key, i) => `${key} = $${i + 1}`).join(', ')}
WHERE (${criteriaKeys
.map((key, i) => `${key} = $${keys.length + i + 1}`)
.join(' AND ')})
AND (${keys.map((key, i) => `${key} != $${i + 1}`).join(' OR ')});
`
return await postQuerySingle(query, [...values, ...criteriaValues])
}
export async function postUpdateID<T>(
table: string,
id: string,
data: { [string]: string }
): Promise<T> {
return await postUpdateWhere(table, { id }, data)
}