@@ -29,7 +29,7 @@ const { boolean } = require('boolean');
2929const { ratelimit } = require ( 'koa-simple-ratelimit' ) ;
3030
3131class API {
32- constructor ( config ) {
32+ constructor ( config , client ) {
3333 this . config = {
3434 ...sharedConfig ( 'API' ) ,
3535 rateLimitIgnoredGlobs : [ ] ,
@@ -41,9 +41,17 @@ class API {
4141 ...this . config . cabin
4242 } ) ;
4343
44+ // initialize redis
45+ this . client = client
46+ ? client
47+ : new Redis ( this . config . redis , cabin , this . config . redisMonitor ) ;
48+
4449 // initialize the app
4550 const app = new Koa ( ) ;
4651
52+ // allow middleware to access redis client
53+ app . context . client = this . client ;
54+
4755 // listen for error and log events emitted by app
4856 app . on ( 'error' , ( err , ctx ) => {
4957 const level = err . status && err . status < 500 ? 'warn' : 'error' ;
@@ -52,16 +60,6 @@ class API {
5260 } ) ;
5361 app . on ( 'log' , cabin . log ) ;
5462
55- // initialize redis
56- const client = new Redis (
57- this . config . redis ,
58- cabin ,
59- this . config . redisMonitor
60- ) ;
61-
62- // allow middleware to access redis client
63- app . context . client = client ;
64-
6563 // override koa's undocumented error handler
6664 app . context . onerror = errorHandler ( false , cabin ) ;
6765
@@ -111,7 +109,7 @@ class API {
111109
112110 return ratelimit ( {
113111 ...this . config . rateLimit ,
114- db : client
112+ db : this . client
115113 } ) ( ctx , next ) ;
116114 } ) ;
117115 }
@@ -169,15 +167,13 @@ class API {
169167 }
170168
171169 // start server on either http or https
172- const server =
170+ this . server =
173171 this . config . protocol === 'https'
174172 ? https . createServer ( this . config . ssl , app . callback ( ) )
175173 : http . createServer ( app . callback ( ) ) ;
176174
177- // expose app, server, client
175+ // expose the app
178176 this . app = app ;
179- this . server = server ;
180- this . client = client ;
181177
182178 // bind listen/close to this
183179 this . listen = this . listen . bind ( this ) ;
0 commit comments