-
-
Notifications
You must be signed in to change notification settings - Fork 34
/
index.js
198 lines (159 loc) · 4.62 KB
/
index.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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
'use strict'
const defaultPg = require('pg')
const fp = require('fastify-plugin')
const addHandler = require('./lib/add-handler.js')
const transactionFailedSymbol = Symbol('transactionFailed')
function transactionUtil (pool, fn, cb) {
pool.connect((err, client, done) => {
if (err) return cb(err)
const shouldAbort = (err) => {
if (err) {
client.query('ROLLBACK', done)
}
return !!err
}
const commit = (err, res) => {
if (shouldAbort(err)) return cb(err)
client.query('COMMIT', (err) => {
done()
if (err) return cb(err)
return cb(null, res)
})
}
client.query('BEGIN', (err) => {
if (shouldAbort(err)) return cb(err)
const promise = fn(client, commit)
if (promise && typeof promise.then === 'function') {
promise.then((res) => commit(null, res), (e) => commit(e))
}
})
})
}
function transact (fn, cb) {
if (cb && typeof cb === 'function') {
return transactionUtil(this, fn, cb)
}
return new Promise((resolve, reject) => {
transactionUtil(this, fn, function (err, res) {
if (err) return reject(err)
return resolve(res)
})
})
}
function extractRequestClient (req, transact) {
if (typeof transact !== 'string') {
return req.pg
}
const requestClient = req.pg[transact]
if (!requestClient) {
throw new Error(`request client '${transact}' does not exist`)
}
return requestClient
}
function fastifyPostgres (fastify, options, next) {
let pg = defaultPg
if (options.pg) {
pg = options.pg
}
if (options.native) {
delete options.native
if (!pg.native) {
console.warn('pg-native not installed, can\'t use native option - fallback to pg module')
} else {
pg = pg.native
}
}
const name = options.name
delete options.name
const pool = new pg.Pool(options)
const db = {
connect: pool.connect.bind(pool),
pool,
Client: pg.Client,
query: pool.query.bind(pool),
transact: transact.bind(pool)
}
fastify.addHook('onClose', (fastify, done) => pool.end(done))
if (name) {
if (db[name]) {
return next(new Error(`fastify-postgres '${name}' is a reserved keyword`))
} else if (!fastify.pg) {
fastify.decorate('pg', Object.create(null))
} else if (fastify.pg[name]) {
return next(new Error(`fastify-postgres '${name}' instance name has already been registered`))
}
fastify.pg[name] = db
} else {
if (fastify.pg) {
if (fastify.pg.pool) {
return next(new Error('fastify-postgres has already been registered'))
}
Object.assign(fastify.pg, db)
} else {
fastify.decorate('pg', db)
}
}
if (!fastify.hasRequestDecorator('pg')) {
fastify.decorateRequest('pg', null)
}
fastify.addHook('onRoute', routeOptions => {
const transact = routeOptions && routeOptions.pg && routeOptions.pg.transact
if (
!transact ||
(typeof transact === 'string' && transact !== name) ||
(name && transact === true)
) {
return
}
const preHandler = async (req, reply) => {
const client = await pool.connect()
if (name) {
if (!req.pg) {
req.pg = Object.create(null)
}
if (client[name]) {
client.release()
throw new Error(`pg client '${name}' is a reserved keyword`)
} else if (req.pg[name]) {
client.release()
throw new Error(`request client '${name}' has already been registered`)
}
req.pg[name] = client
} else {
if (req.pg) {
client.release()
throw new Error('request client has already been registered')
} else {
req.pg = client
}
}
await client.query('BEGIN')
}
const onError = (req, reply, error, done) => {
req[transactionFailedSymbol] = true
extractRequestClient(req, transact).query('ROLLBACK', done)
}
const onSend = async (req) => {
const requestClient = extractRequestClient(req, transact)
if (requestClient) {
try {
if (!req[transactionFailedSymbol]) {
await requestClient.query('COMMIT')
}
} finally {
requestClient.release()
}
}
}
routeOptions.preHandler = addHandler(routeOptions.preHandler, preHandler)
routeOptions.onError = addHandler(routeOptions.onError, onError)
routeOptions.onSend = addHandler(routeOptions.onSend, onSend)
})
next()
}
module.exports = fp(fastifyPostgres, {
fastify: '5.x',
name: '@fastify/postgres'
})
module.exports.default = fastifyPostgres
module.exports.fastifyPostgres = fastifyPostgres