@germanescobar/prisma-transactional
v0.6.0
Published
Adds support for prisma transactions across functions
Downloads
368
Maintainers
Readme
Prisma Transactional Context
This package adds support for transactions across functions without having to explicitly pass them around (argument drilling).
Underneath, it uses the AsyncLocalStorage to store the transaction and Proxy object to wrap the prisma client.
It also supports savepoints to mimic nested transactions in databases that support this feature (tested in PostgreSQL only for now). Savepoints are enable by default, see below on how to disable them.
Installation
npm install @germanescobar/prisma-transactional
Usage
import { AsyncLocalStorage } from 'node:async_hooks'
import createPrismaTransactionalProxy from '@germanescobar/prisma-transactional'
// create the instance of AsyncLocalStorage, you may want to define and export this
// from another file to reuse it across the code
const asyncLocalStorage = new AsyncLocalStorage();
const originalPrisma = new PrismaClient(...);
const prisma = createPrismaTransactionalProxy(originalPrisma, asyncLocalStorage);
// use prisma as you would normally do
async function executeTransfer() {
prisma.$transaction(tx => {
// but now you can call other functions inside the transaction
await transfer('111', '222', 100);
});
}
async function transfer(from, to, amount) {
// all these queries will run inside the transaction created previously
const fromAccount = await prisma.account.findUniqueOrThrow({ where: { id: from }});
await prisma.account.update({ where: { id: from }, data: { balance: fromAccount.balance - amount } });
const toAccount = await prisma.account.findUniqueOrThrow({ where: { id: to }});
await prisma.account.update({ where: { id: to }, data: { balance: toAccount.balance + amount } });
}
To disable savepoints ("nested transactions") use the enableSavepoints
option (they are enabled by default):
const prisma = createPrismaTransactionalProxy(
originalPrisma,
asyncLocalStorage,
{ enableSavepoints: false } // disables savepoints
);