Skip to content

Commit 372c3d3

Browse files
committed
Added multiple pool support
1 parent 954d787 commit 372c3d3

File tree

1 file changed

+46
-13
lines changed

1 file changed

+46
-13
lines changed

plugin.js

Lines changed: 46 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,26 +3,61 @@
33
const fp = require('fastify-plugin')
44
const oracledb = require('oracledb')
55

6-
function fastifyOracleDB (fastify, options, next) {
7-
const close = function (fastify, done) {
8-
fastify.oracle.close(done)
6+
const close = function (fastify, done) {
7+
Object.keys(fastify.oracle)
8+
.forEach(key => {
9+
if (fastify.oracle[key].pool) {
10+
fastify.oracle[key].pool.close(done)
11+
}
12+
})
13+
14+
if (fastify.oracle.pool) {
15+
fastify.oracle.pool.close(done)
16+
}
17+
}
18+
19+
function decorateFastifyInstance(pool, fastify, options, next) {
20+
const oracle = {
21+
getConnection: pool.getConnection.bind(pool),
22+
pool
23+
};
24+
25+
if (options.name) {
26+
if (!fastify.oracle) {
27+
fastify.decorate('oracle', Object.assign(oracle, { db: oracledb }))
28+
}
29+
30+
if (fastify.oracle[options.name]) {
31+
return next(new Error('Connection name has already been registered: ' + options.name))
32+
}
33+
34+
fastify.oracle[options.name] = oracle
35+
} else {
36+
if (fastify.oracle) {
37+
return next(new Error('fastify-oracle has already been registered'))
38+
}
39+
else {
40+
fastify.decorate('oracle', Object.assign(oracle, { db: oracledb }))
41+
}
942
}
1043

44+
fastify.addHook('onClose', close)
45+
46+
return next()
47+
}
48+
49+
function fastifyOracleDB(fastify, options, next) {
1150
if (options.client) {
1251
if (oracledb.Pool.prototype.isPrototypeOf(options.client) === false) {
1352
return next(Error('supplied client must be an instance of oracledb.pool'))
1453
}
15-
fastify.decorate('oracle', options.client)
16-
fastify.addHook('onClose', close)
17-
return next()
54+
return decorateFastifyInstance(options.client, fastify, options, next)
1855
}
1956

2057
if (options.poolAlias) {
2158
const pool = oracledb.getPool(options.poolAlias)
22-
if (!pool) return next('could not get default pool from oracledb instance')
23-
fastify.decorate('oracle', pool)
24-
fastify.addHook('onClose', close)
25-
return next()
59+
if (!pool) return next(Error('could not get default pool from oracledb instance'))
60+
return decorateFastifyInstance(pool, fastify, options, next)
2661
}
2762

2863
if (!options.pool) {
@@ -31,9 +66,7 @@ function fastifyOracleDB (fastify, options, next) {
3166

3267
oracledb.createPool(options.pool, (err, pool) => {
3368
if (err) return next(err)
34-
fastify.decorate('oracle', pool)
35-
fastify.addHook('onClose', close)
36-
next()
69+
return decorateFastifyInstance(pool, fastify, options, next)
3770
})
3871
}
3972

0 commit comments

Comments
 (0)