3
3
const fp = require ( 'fastify-plugin' )
4
4
const oracledb = require ( 'oracledb' )
5
5
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
+ }
9
42
}
10
43
44
+ fastify . addHook ( 'onClose' , close )
45
+
46
+ return next ( )
47
+ }
48
+
49
+ function fastifyOracleDB ( fastify , options , next ) {
11
50
if ( options . client ) {
12
51
if ( oracledb . Pool . prototype . isPrototypeOf ( options . client ) === false ) {
13
52
return next ( Error ( 'supplied client must be an instance of oracledb.pool' ) )
14
53
}
15
- fastify . decorate ( 'oracle' , options . client )
16
- fastify . addHook ( 'onClose' , close )
17
- return next ( )
54
+ return decorateFastifyInstance ( options . client , fastify , options , next )
18
55
}
19
56
20
57
if ( options . poolAlias ) {
21
58
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 )
26
61
}
27
62
28
63
if ( ! options . pool ) {
@@ -31,9 +66,7 @@ function fastifyOracleDB (fastify, options, next) {
31
66
32
67
oracledb . createPool ( options . pool , ( err , pool ) => {
33
68
if ( err ) return next ( err )
34
- fastify . decorate ( 'oracle' , pool )
35
- fastify . addHook ( 'onClose' , close )
36
- next ( )
69
+ return decorateFastifyInstance ( pool , fastify , options , next )
37
70
} )
38
71
}
39
72
0 commit comments