selfish
4/30/2016 - 11:16 PM

Node.js simple MySQL DB driver

Node.js simple MySQL DB driver

// Require libraries:
const _ = require('lodash');
const mysql = require('mysql');

// Load configuration for DB server:
var config = require('./config');

// Create DB connection object:
var conn = mysql.createConnection(config.db);

// Connect to DB
// Source: https://github.com/felixge/node-mysql#establishing-connections
conn.connect(function (err) {
    // In case of connection error, log and crash:
    if (err) {
        console.error('Error connecting to DB: ' + err.stack);
        throw err;
    }
    // Otherwise log connection success:
    console.log('Connected to DB with thread ID: ' + conn.threadId);
});

/**
 * Helper function to query DB.
 *
 * @param query - string - query text
 * @param params [optional] - array - params for query
 * @param cb - function - callback(err, rows, fields)
 */
function queryDB(query, params, cb) {
    // format query for server, if params is not provided, use empty array:
    var sql = mysql.format(query, _.isArray(params) ? params : []);
    // Query server. If cb is missing, optional params was not provided, use second argument as cb:
    conn.query(sql, _.isFunction(cb) ? cb : params);
}

// Expose query method:
module.exports = {
    query: queryDB
};