Skip to content

Instantly share code, notes, and snippets.

@dkleehammer
Last active December 31, 2015 15:49
Show Gist options
  • Save dkleehammer/8008942 to your computer and use it in GitHub Desktop.
Save dkleehammer/8008942 to your computer and use it in GitHub Desktop.
Asynchronous node connection object (prerequisites: Node v0.11.2+ using --harmony flag). To run, npm install, node --harmony main.js
"use strict";
exports = module.exports = function(app) {
var pool = app.get('pool'), Q = require('Q');
return {
execute: Q.async(function*(sql) {
var params = Array.prototype.slice.call(arguments, 1);
var deferred = Q.defer();
try {
pool.getConnection(function(err, connection) {
if (err) {
console.error(err);
// deferred.reject(err);
throw err;
}
connection.query(sql, params, function(err, results) {
connection.release();
if (err) {
console.error(err);
deferred.reject(err);
} else {
deferred.resolve((sql.indexOf('INSERT INTO') === 0 ? results.insertId : results));
}
});
});
} catch (err) {
console.error(err);
deferred.reject(err);
}
return deferred.promise;
})
}
}
"use strict";
var express = require('express'),
app = express(),
mysql = require('mysql'),
Q = require('Q');
// --------------------------------------------
// Configuration
// --------------------------------------------
var pool = mysql.createPool({
host: '',
user: '',
password: '',
database: '',
});
app.set('pool', pool);
app.set('database', require('./lib/connection.js')(app));
app.use(express.logger());
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.set('port', 3000);
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
app.use(app.router);
// --------------------------------------------
// Route for testing
// --------------------------------------------
app.get('/', Q.async(function*(req, res) {
var db = app.get('database');
var user = yield db.execute("SELECT * FROM users WHERE user_id=?", 1);
return res.json(user);
}));
// --------------------------------------------
// Start server
// --------------------------------------------
app.listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
{
"name": "async",
"version": "0.0.0",
"description": "",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Daniel Kleehammer",
"license": "MIT",
"dependencies": {
"q": "~0.9.7",
"mysql": "~2.0.0-rc2",
"express": "~3.4.7"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment