Created
May 24, 2016 10:33
-
-
Save xzer/c60beaf4df1e0e679b408a415ffde38e to your computer and use it in GitHub Desktop.
Promise friendly node pg wrapper
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 createDb = function(addr){ | |
console.log("connecting to", addr); | |
var client = new pg.Client(addr); | |
var qfn = client.query; | |
client.query = function(){ | |
var len = arguments.length; | |
if(typeof arguments[len-1] === "function"){ | |
var callback = arguments[len-1]; | |
arguments[len-1] = function(error, result){ | |
if(error){ | |
throw error; | |
}else{ | |
callback.call(this, result); | |
} | |
}; | |
} | |
var result = qfn.apply(this, arguments) | |
result.on("error", exit); | |
} | |
client.executeAsync = function(){ | |
var THIS = this; | |
var args = [].slice.call(arguments); | |
return new Promise(function(resolve, reject){ | |
args.push(function(error, result){ | |
resolve(result); | |
}) | |
THIS.query.apply(THIS, args) | |
}); | |
} | |
client.queryAsync = function(){ | |
var THIS = this; | |
var args = [].slice.call(arguments); | |
var len = args.length; | |
if(typeof args[len-1] === "function"){ | |
return new Promise(function(resolve, reject){ | |
var cb = args[len-1]; | |
args[len-1] = function(result){ | |
resolve(cb(result)); | |
} | |
THIS.query.apply(THIS, args) | |
}); | |
}else{ | |
var q = THIS.query.apply(THIS, args); | |
q.onRow = function(callback){ | |
q.on("row", callback); | |
}; | |
q.onEnd = function(callback){ | |
return new Promise(function(resolve, reject){ | |
q.on("end", function(){ | |
resolve(callback.apply()); | |
}); | |
}); | |
} | |
return q; | |
} | |
} | |
client.on('error', function(error) { | |
console.log("got error"); | |
throw error; | |
}) | |
client.connect(); | |
return client; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment