11const mysql = require ( 'mysql' ) ;
22const settings = require ( '../utils' ) . settings ;
33const logger = require ( '../utils' ) . logger ;
4+ const dbStatus = require ( '../utils' ) . dbStatus ;
45
56let db = settings . db . prod ;
67
78if ( process . env . spec === "true" ) {
89 db = settings . db . spec
910}
1011
11- var connection = mysql . createPool ( {
12+ var pool = mysql . createPool ( {
1213 connectionLimit : 10 ,
1314 host : db . host ,
1415 socketPath : db . socketPath ,
@@ -20,15 +21,68 @@ var connection = mysql.createPool({
2021
2122module . exports . init = function ( cb ) {
2223
23- connection . on ( 'connection' , connection => {
24+ pool . on ( 'connection' , connection => {
2425 logger ( '[db]: connected as id ' + connection . threadId ) ;
2526 cb ( ) ;
2627 } ) ;
2728
29+ pool . getConnection ( ( err , connection ) => {
30+ if ( err ) {
31+ return dbStatus ( false ) ;
32+ }
33+ connection . query ( 'SELECT 1' , [ ] , ( ) => {
34+ dbStatus ( true ) ;
35+ connection . release ( ) ;
36+ } ) ;
37+ } ) ;
38+
2839 // Keep connection alive
2940 setInterval ( ( ) => {
30- connection . query ( 'SELECT 1' ) ;
41+ pool . getConnection ( ( err , connection ) => {
42+ if ( err ) {
43+ return dbStatus ( false ) ;
44+ }
45+ connection . query ( 'SELECT 1' , [ ] , ( ) => {
46+ dbStatus ( true ) ;
47+ connection . release ( ) ;
48+ } ) ;
49+ } ) ;
3150 } , db . keepAliveInterval ) ;
3251} ;
3352
34- module . exports . connection = connection ;
53+ module . exports . connection = {
54+ query : function ( ) {
55+ let queryArgs = Array . prototype . slice . call ( arguments ) ,
56+ events = [ ] ,
57+ eventNameIndex = { } ;
58+
59+ pool . getConnection ( ( err , conn ) => {
60+ if ( err ) {
61+ if ( eventNameIndex . error ) {
62+ eventNameIndex . error ( ) ;
63+ }
64+ }
65+ if ( conn ) {
66+ let q = conn . query . apply ( conn , queryArgs ) ;
67+ q . on ( 'end' , ( ) => {
68+ conn . release ( ) ;
69+ } ) ;
70+
71+ events . forEach ( args => {
72+ q . on . apply ( q , args ) ;
73+ } ) ;
74+ }
75+ } ) ;
76+
77+ return {
78+ on : function ( eventName , callback ) {
79+ events . push ( Array . prototype . slice . call ( arguments ) ) ;
80+ eventNameIndex [ eventName ] = callback ;
81+ return this ;
82+ }
83+ } ;
84+ } ,
85+ escape : val => pool . escape ( val )
86+ } ;
87+
88+ //module.exports.connection = connection;
0 commit comments