Completely promisify pg driver

This commit is contained in:
Timothy Warren 2016-11-14 20:21:02 -05:00
parent 7fbbff41c8
commit 5dd42e07a7
2 changed files with 8 additions and 13 deletions

View File

@ -32,12 +32,14 @@ class Pg extends Adapter {
} }
if (connectionString !== '') { if (connectionString !== '') {
instance = new pg.Client(connectionString); let conn = new pg.Client(connectionString);
instance.connect(err => { conn.connect(err => {
if (err) { if (err) {
throw new Error(err); throw new Error(err);
} }
}); });
instance = Promise.resolve(conn);
} }
super(instance); super(instance);
@ -67,32 +69,25 @@ class Pg extends Adapter {
* *
* @param {String} sql - The sql with placeholders * @param {String} sql - The sql with placeholders
* @param {Array} params - The values to insert into the query * @param {Array} params - The values to insert into the query
* @param {Function} [callback] - Callback to run when a response is recieved
* @return {void|Promise} - Returns a promise if no callback is provided * @return {void|Promise} - Returns a promise if no callback is provided
*/ */
execute (/* sql, params, callback */) { execute (sql, params) {
let args = getArgs('sql:string, [params]:array, [callback]:function', arguments);
// Replace question marks with numbered placeholders, because this adapter is different... // Replace question marks with numbered placeholders, because this adapter is different...
let count = 0; let count = 0;
args.sql = args.sql.replace(/\?/g, () => { sql = sql.replace(/\?/g, () => {
count++; count++;
return `$${count}`; return `$${count}`;
}); });
if (!args.callback) { return this.instance.then(conn => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.instance.query(args.sql, args.params, (err, result) => conn.query(sql, params, (err, result) =>
(err) (err)
? reject(err) ? reject(err)
: resolve(this.transformResult(result)) : resolve(this.transformResult(result))
); );
}); });
}
return this.instance.query(args.sql, args.params, (err, origResult) => {
let result = this.transformResult(origResult);
return args.callback(err, result);
}); });
} }
} }