Created
August 9, 2017 18:35
-
-
Save rla/39cf3b187a51bafae2889f0c1a0c6ad4 to your computer and use it in GitHub Desktop.
Node.js MySQL transaction with async/await
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
// 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.'); | |
} | |
}; |
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
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