Skip to content

Instantly share code, notes, and snippets.

@loujaybee
Last active October 1, 2018 08:13
Show Gist options
  • Save loujaybee/7ec01fe558ec0327b7b5c5285c612bd3 to your computer and use it in GitHub Desktop.
Save loujaybee/7ec01fe558ec0327b7b5c5285c612bd3 to your computer and use it in GitHub Desktop.
Postgres transaction clean up
const db = require('../../database/db.js');
// The following would be library code, touched barely ever
const _executeTransaction = async(transaction) => {
try {
return await db.tx(transaction);
} catch (e) {
console.log(e);
// Handle DB error
}
};
const _buildTransaction = ( queries = [] ) =>
( t ) => {
// TODO: Handle logic of the queries object structure
const preparedQueries = queries.map( ({ method, query, args }) =>
t[method || 'any'](query, args || [])
);
return t.batch(preparedQueries);
};
const doBoth = (queries) => {
const temp = _buildTransaction(queries);
return _executeTransaction(temp);
};
// The following is how the code would be consumed...
executeTransaction([{
query: 'SELECT * FROM oauth_code'
}, {
query: 'SELECT * FROM oauth_code'
}])
.then( (data) => {
console.log(data);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment