UNPKG

@transactional/prisma

Version:

"@transactional/prisma" is an npm package that offers a "@Transactional" method decorator for running your queries inside a transaction seamlessly. It achieves this by leveraging AsyncLocalStorage.

48 lines (47 loc) 2.44 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.prismaTransactional = void 0; const client_1 = require("@prisma/client"); const core_1 = require("@transactional/core"); const flat_transaction_1 = require("./flat-transaction"); const prismaTransactional = client_1.Prisma.defineExtension((prisma) => { return prisma.$extends({ query: { $allOperations: ({ args, model, operation, query }) => __awaiter(void 0, void 0, void 0, function* () { const store = core_1.TRANSACTIONAL_CONTEXT.getStore(); // query was not run in a @Transactional or was not allowed to use transaction if (!store) { return query(args); } /* this is the first query to run inside a transactional function, so we need to create and attach the transaction to the store */ if (!store.tx) { /* create a transaction and assign it to the current store */ store.tx = new Promise((resolve, reject) => __awaiter(void 0, void 0, void 0, function* () { const tx = yield (0, flat_transaction_1.transaction)(prisma, store.options); store.$commit = tx.$commit; store.$rollback = tx.$rollback; resolve(tx); })); } const tx = yield store.tx; if (model) { return tx[model][operation](args); } else { return tx[operation](args); } }), }, }); }); exports.prismaTransactional = prismaTransactional;