Created
January 27, 2020 05:11
-
-
Save jsuryahyd/a3d737f72a3fd158a6b0650ed5bcff26 to your computer and use it in GitHub Desktop.
promisifying transaction related functions of node mysql library
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
getPromisifiedConnection(pool) { | |
return util.promisify(pool.getConnection).bind(pool); | |
} | |
getPromisifiedBeginTransaction(connection) { | |
return util.promisify(connection.beginTransaction.bind(connection)); | |
} | |
getPromisifiedQuery(connection) { | |
util.promisify((sql, options, cb) => | |
connection.query(sql, options, (err, results) => cb(err, results)) | |
); | |
} | |
getPromisifiedRollBack(connection) { | |
util.promisify(connection.rollback.bind(connection)); | |
} | |
getPromisifiedCommit(connection) { | |
util.promisify(connection.commit.bind(connection)); | |
} | |
async getPromisifiedDbFuncs(pool) { | |
const getConnection = util.promisify(pool.getConnection).bind(pool); | |
/** @type {import('mysql').PoolConnection} */ | |
const connection = await getConnection().catch( | |
/** @type {import('mysql').MysqlError} */ err => errorLog.error(err) | |
); | |
if (!connection) throw new Error("could not get pool connection"); | |
//bindings are important. | |
const beginTransactionPromise = util.promisify( | |
connection.beginTransaction.bind(connection) | |
); | |
// const queryPromise = util.promisify(connection.query.bind(connection)); | |
const queryPromise = util.promisify((sql, options, cb) => | |
connection.query(sql, options, (err, results) => cb(err, results)) | |
); | |
const rollBackPromise = util.promisify( | |
connection.rollback.bind(connection) | |
); | |
const commitPromise = util.promisify(connection.commit.bind(connection)); | |
return { | |
beginTransactionPromise, | |
queryPromise, | |
rollBackPromise, | |
commitPromise, | |
connection, | |
pool | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment