Guest User

Untitled

a guest
Jul 18th, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. const mysql = require('mysql')
  2. const winston = require('winston')
  3.  
  4. const pool = mysql.createPool({
  5. connectionLimit: 10,
  6. host: process.env.DB_HOST,
  7. user: process.env.DB_USER,
  8. password: process.env.DB_PASS,
  9. database: process.env.DB_NAME
  10. })
  11.  
  12. function queryData(query) {
  13. return getConnection().then((connection) => {
  14. return executeQuery(query, connection)
  15. }).then((response) => {
  16. releaseConnection(response.connection)
  17. return response.results
  18. }).catch((response) => {
  19. releaseConnection(response.connection)
  20. throw response.error
  21. })
  22. }
  23.  
  24. function processData(query) {
  25. return getConnection().then((connection) => {
  26. return executeQuery(query, connection)
  27. }).then((response) => {
  28. releaseConnection(response.connection)
  29. return response.results
  30. }).catch((response) => {
  31. releaseConnection(response.connection)
  32. throw response.error
  33. })
  34. }
  35.  
  36. function getConnection() {
  37. return new Promise((resolve, reject) => {
  38. pool.getConnection((err, connection) => {
  39. if (err) reject(err)
  40. resolve(connection)
  41. })
  42. })
  43. }
  44.  
  45. const releaseConnection = (connection) => connection && connection.release()
  46.  
  47. function executeQuery(query, connection) {
  48. return new Promise((resolve, reject) => {
  49. connection.query(query, function (error, results, fields) {
  50. if (error) {
  51. winston.log('debug', query)
  52. const result = { error: error, connection: connection }
  53. reject(result)
  54. }
  55.  
  56. const result = { results: results, fields: fields, connection: connection }
  57. resolve(result)
  58. })
  59. })
  60. }
  61.  
  62. module.exports = {
  63. query: queryData,
  64. process: processData
  65. }
Add Comment
Please, Sign In to add comment