Skip to content

Instantly share code, notes, and snippets.

@rla
Created August 9, 2017 18:35
Show Gist options
  • Save rla/39cf3b187a51bafae2889f0c1a0c6ad4 to your computer and use it in GitHub Desktop.
Save rla/39cf3b187a51bafae2889f0c1a0c6ad4 to your computer and use it in GitHub Desktop.
Node.js MySQL transaction with async/await
// Executes the given function inside
// a transaction.
exports.transaction = async (fn) => {
assert.equal(typeof fn, 'function');
// Aquire a connection.
const connection = await aquire(pool);
debug('Aquired a connection.');
try {
// Begin the transaction.
await begin(connection);
debug('Started the transaction.');
try {
// Run queries.
const result = await fn(connection);
debug('Ran the queries.');
// Commit the transaction.
await commit(connection);
debug('Committed the transaction.');
// Return query results.
return result;
} catch (err) {
// Rollback the transaction.
await rollback(connection);
debug('Rolled back the transaction.');
throw err;
}
} finally {
// Release the connection.
connection.release();
debug('Released the connection.');
}
};
exports.save = async (company) => {
return mysql.transaction(async (connection) => {
const exists = await companiesRepo.exists(connection, company.name);
if (exists) {
const errors = new Errors();
errors.add('name', 'Company with the same name exists.');
throw new ValidationError(errors);
}
return companiesRepo.save(connection, company);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment