@drmikehopper/express-knex-auto-trx
v0.1.5
Published
Express middleware for automatically managing Knex.js database transactions.
Readme
express-knex-auto-trx
Express middleware for automatically managing Knex.js database transactions.
Motivation
This middleware will automatically:
- Start a
knexdatabase transaction for each inbound request. - Provide a
getTrx()function that can berequiredby your Express route handlers.- Your code can get the current transaction without needing the
reqobject, which is helpful when using data service layers that are decoupled from Express.
- Your code can get the current transaction without needing the
- Automatically
commitorrollbackeach transaction based on the HTTP response status code:- responses with a
400or above willrollback - all other responses will
commit.
- responses with a
How It Works
- Uses cls-hooked to assign a unique transaction to each request
- Uses on-finished to inspect the response
statusCodeand eithercommitorrollbackthe transaction
Usage
Connect the Middleware:
const express = require('express');
const { knexAutoTrx } = require('./middleware/express-knex-auto-trx');
const knex = require('knex')(
require('knexfile')[process.env.NODE_ENV || 'development']
);
app.use(knexAutoTrx(knex));Then use the getTrx function as a replacement for the knex object/function:
const { getTrx } = require('../middleware/express-knex-auto-trx');
const express = require('express');
const router = express.Router();
router.post('/users', (req, res, next) => {
try {
const [savedUser] = await getTrx() // each request will get its own transaction
.insert(userData)
.into('users')
.returning('*');
res.status(200).json(savedUser);
} catch (err) {
next(err);
}
});
module.exports = router;