Skip to content

Instantly share code, notes, and snippets.

@jacksmith15
Last active August 22, 2023 15:45
Show Gist options
  • Save jacksmith15/b7f70a1945e9770f727bbf5615a281e6 to your computer and use it in GitHub Desktop.
Save jacksmith15/b7f70a1945e9770f727bbf5615a281e6 to your computer and use it in GitHub Desktop.
express-knex-transaction-middleware.ts

Middleware factory for using a single transaction per request. Transactions are only started if a downstream handler requests one. If a transaction is started by the handler, it is automatically committed or rolled back once the handler completes.

Usage:

Enable the middleware:

app.use(makeDatabaseTransactionMiddleware(knex));

In handler:

async function handleRequest(req, res) {
 const transaction = req.getTransaction();
 // Potentially failing logic here
}
import type { Knex } from 'knex';
function makeDatabaseTransactionMiddleware(knex: Knex) {
async function databaseTransactionMiddleware(req, res, next) {
let transaction;
function getTransaction() {
if (!transaction) {
transaction = knex.transaction();
}
return transaction;
}
try {
req.getTransaction = getTransaction;
await next();
if (transaction) {
await transaction.commit();
}
} catch {
if (transaction) {
await transaction.rollback();
}
}
}
return databaseTransactionMiddleware;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment