Created
November 1, 2017 02:28
-
-
Save bugzbrown/3bed408b4529e3f4cd4f954f66d6b6a8 to your computer and use it in GitHub Desktop.
MySQL helper for node apps
This file contains 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
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