Skip to content

Instantly share code, notes, and snippets.

@bugzbrown
Created November 1, 2017 02:28
Show Gist options
  • Save bugzbrown/3bed408b4529e3f4cd4f954f66d6b6a8 to your computer and use it in GitHub Desktop.
Save bugzbrown/3bed408b4529e3f4cd4f954f66d6b6a8 to your computer and use it in GitHub Desktop.
MySQL helper for node apps
var mysql = require('mysql')
, async = require('async')
, config = require('config');
var state = {
pool: null,
mode: null,
}
exports.connect = function(done) {
state.pool = mysql.createPool(config.database.mysql)
done()
}
exports.get = function() {
return state.pool
}
exports.fixtures = function(data) {
var pool = state.pool
if (!pool) return done(new Error('Missing database connection.'))
var names = Object.keys(data.tables)
async.each(names, function(name, cb) {
async.each(data.tables[name], function(row, cb) {
var keys = Object.keys(row)
, values = keys.map(function(key) { return "'" + row[key] + "'" })
pool.query('INSERT INTO ' + name + ' (' + keys.join(',') + ') VALUES (' + values.join(',') + ')', cb)
}, cb)
}, done)
}
exports.drop = function(tables, done) {
var pool = state.pool
if (!pool) return done(new Error('Missing database connection.'))
async.each(tables, function(name, cb) {
pool.query('DELETE * FROM ' + name, cb)
}, done)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment