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.

74 lines (73 loc) 3.07 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.transaction = void 0; const ROLLBACK = { [Symbol.for("prisma.client.extension.rollback")]: true }; function transaction(prisma, options) { return __awaiter(this, void 0, void 0, function* () { if (!isTransactionSupported(prisma)) { throw new Error("Transactions are not supported by this client"); } let setTxClient; let commit; let rollback; const txPromise = new Promise((resolve, reject) => { commit = () => resolve(undefined); rollback = () => reject(ROLLBACK); }); const txClient = new Promise((resolve, reject) => { setTxClient = (tx) => resolve(tx); }); const tx = prisma["$transaction"]((tx) => { setTxClient(tx); return txPromise; }, options); return new Proxy(yield txClient, { get(target, prop) { if (prop === "$commit") { return () => __awaiter(this, void 0, void 0, function* () { commit(); // await for tx to be resolved before resolving yield tx; }); } if (prop === "$rollback") { return () => __awaiter(this, void 0, void 0, function* () { rollback(); try { yield tx; } catch (error) { // rollback function should resolve with `undefined` in case it rolledback // successfully if (error[Symbol.for("prisma.client.extension.rollback")]) { return undefined; } // and it should throw any other errors thrown by tx throw error; } }); } return target[prop]; }, }); }); } exports.transaction = transaction; function isTransactionSupported(prisma) { if ("$transaction" in prisma && typeof prisma["$transaction"] === "function") { return true; } else { return false; } }