Created
July 18, 2018 21:43
-
-
Save kirill3333/b95a5f52a4efe7fa279735623c8c5f30 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const mysql = require('mysql') | |
const winston = require('winston') | |
const pool = mysql.createPool({ | |
connectionLimit: 10, | |
host: process.env.DB_HOST, | |
user: process.env.DB_USER, | |
password: process.env.DB_PASS, | |
database: process.env.DB_NAME | |
}) | |
function queryData(query) { | |
return getConnection().then((connection) => { | |
return executeQuery(query, connection) | |
}).then((response) => { | |
releaseConnection(response.connection) | |
return response.results | |
}).catch((response) => { | |
releaseConnection(response.connection) | |
throw response.error | |
}) | |
} | |
function processData(query) { | |
return getConnection().then((connection) => { | |
return executeQuery(query, connection) | |
}).then((response) => { | |
releaseConnection(response.connection) | |
return response.results | |
}).catch((response) => { | |
releaseConnection(response.connection) | |
throw response.error | |
}) | |
} | |
function getConnection() { | |
return new Promise((resolve, reject) => { | |
pool.getConnection((err, connection) => { | |
if (err) reject(err) | |
resolve(connection) | |
}) | |
}) | |
} | |
const releaseConnection = (connection) => connection && connection.release() | |
function executeQuery(query, connection) { | |
return new Promise((resolve, reject) => { | |
connection.query(query, function (error, results, fields) { | |
if (error) { | |
winston.log('debug', query) | |
const result = { error: error, connection: connection } | |
reject(result) | |
} | |
const result = { results: results, fields: fields, connection: connection } | |
resolve(result) | |
}) | |
}) | |
} | |
module.exports = { | |
query: queryData, | |
process: processData | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment