{"id":17340848,"url":"https://github.com/kenfdev/prisma-auto-transaction-poc","last_synced_at":"2025-04-14T19:07:43.075Z","repository":{"id":88345819,"uuid":"502059637","full_name":"kenfdev/prisma-auto-transaction-poc","owner":"kenfdev","description":null,"archived":false,"fork":false,"pushed_at":"2023-12-15T05:07:52.000Z","size":120,"stargazers_count":24,"open_issues_count":2,"forks_count":2,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-04-14T19:07:38.578Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://dev.to/kenfdev/cross-module-transaction-with-prisma-5d08","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/kenfdev.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2022-06-10T13:46:51.000Z","updated_at":"2024-06-20T16:07:42.000Z","dependencies_parsed_at":"2023-12-15T06:25:49.054Z","dependency_job_id":"e3c4badd-382d-4822-892e-3a4668ae584c","html_url":"https://github.com/kenfdev/prisma-auto-transaction-poc","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kenfdev%2Fprisma-auto-transaction-poc","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kenfdev%2Fprisma-auto-transaction-poc/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kenfdev%2Fprisma-auto-transaction-poc/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kenfdev%2Fprisma-auto-transaction-poc/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kenfdev","download_url":"https://codeload.github.com/kenfdev/prisma-auto-transaction-poc/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248943456,"owners_count":21186958,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-15T15:46:45.983Z","updated_at":"2025-04-14T19:07:43.037Z","avatar_url":"https://github.com/kenfdev.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Prisma cross module transaction PoC\n\nThis is a PoC to see if cross module transaction is possible with Prisma.\n\nDespite Prisma being able to use interactive transaction, it forces you to use a newly created `Prisma.TransactionClient` as follows:\n\n```ts\n// copied from official docs https://www.prisma.io/docs/concepts/components/prisma-client/transactions#batchbulk-operations\n\nawait prisma.$transaction(async (prisma) =\u003e {\n  // 1. Decrement amount from the sender.\n  const sender = await prisma.account.update({\n    data: {\n      balance: {\n        decrement: amount,\n      },\n    },\n    where: {\n      email: from,\n    },\n  });\n  // 2. Verify that the sender's balance didn't go below zero.\n  if (sender.balance \u003c 0) {\n    throw new Error(`${from} doesn't have enough to send ${amount}`);\n  }\n  // 3. Increment the recipient's balance by amount\n  const recipient = prisma.account.update({\n    data: {\n      balance: {\n        increment: amount,\n      },\n    },\n    where: {\n      email: to,\n    },\n  });\n  return recipient;\n});\n```\n\nThis becomes troublesome when you're working with a enterprise-ish project where multiple repositories need to work in a single transaction.\n\nThis PoC got inspiration from [this](https://github.com/prisma/prisma/issues/5729#issuecomment-959137819) issue comment and uses the power of [cls-hooked](https://www.npmjs.com/package/cls-hooked) to be able to pass the `Prisma.TransactionClient` between modules.\n\nHence, you'll be able to write code like this.\n\n```ts\nexport class CreateOrder {\n  private readonly orderRepo: OrderRepository;\n  private readonly notificationRepo: NotificationRepository;\n  private readonly transactionScope: TransactionScope;\n  constructor(\n    orderRepo: OrderRepository,\n    notificationRepo: NotificationRepository,\n    transactionScope: TransactionScope\n  ) {\n    this.orderRepo = orderRepo;\n    this.notificationRepo = notificationRepo;\n    this.transactionScope = transactionScope;\n  }\n\n  async execute({ productIds }: CreateOrderInput) {\n    const order = Order.create(productIds);\n\n    // create a transaction scope inside the Application layer\n    await this.transactionScope.run(async () =\u003e {\n      // call multiple repository methods inside the transaction\n      // if either fails, the transaction will rollback\n      await this.orderRepo.create(order);\n      await this.notificationRepo.send(\n        `Successfully created order: ${order.id}`\n      );\n    });\n  }\n}\n```\n\nFurthermore, you can call a transaction from within the repository, too. Since somebody might forget to use the transaction scope in the application layer.\n\n```ts\nexport class PrismaOrderRepository implements OrderRepository {\n  private readonly clientManager: PrismaClientManager;\n  private readonly transactionScope: TransactionScope;\n\n  constructor(\n    clientManager: PrismaClientManager,\n    transactionScope: TransactionScope\n  ) {\n    this.clientManager = clientManager;\n    this.transactionScope = transactionScope;\n  }\n\n  async create(order: Order): Promise\u003cvoid\u003e {\n    // you don't need to care if you're inside a transaction or not\n    await this.transactionScope.run(async () =\u003e {\n      const prisma = this.clientManager.getClient();\n      const newOrder = await prisma.order.create({\n        data: {\n          id: order.id,\n        },\n      });\n\n      for (const productId of order.productIds) {\n        await prisma.orderProduct.create({\n          data: {\n            id: uuid(),\n            orderId: newOrder.id,\n            productId,\n          },\n        });\n      }\n    });\n  }\n}\n```\n\nThe truth is, it's just a little hack in the `PrismaTransactionScope`. It'll only create a transaction if you are not already inside one.\n\n\n```ts\nexport class PrismaTransactionScope implements TransactionScope {\n  private readonly prisma: PrismaClient;\n  private readonly transactionContext: cls.Namespace;\n\n  constructor(prisma: PrismaClient, transactionContext: cls.Namespace) {\n    this.prisma = prisma;\n    this.transactionContext = transactionContext;\n  }\n\n  async run(fn: () =\u003e Promise\u003cvoid\u003e): Promise\u003cvoid\u003e {\n    // check if the transaction client is present or not\n    const prisma = this.transactionContext.get(\n      PRISMA_CLIENT_KEY\n    ) as Prisma.TransactionClient;\n\n    if (prisma) {\n      // if the transaction client is present, just execute the callback\n      await fn();\n    } else {\n      // if the transaction client is not present, create the transaction and save the Prisma.TransactionClient inside the cls to be used later on.\n      await this.prisma.$transaction(async (prisma) =\u003e {\n        await this.transactionContext.runPromise(async () =\u003e {\n          this.transactionContext.set(PRISMA_CLIENT_KEY, prisma);\n\n          try {\n            await fn();\n          } catch (err) {\n            this.transactionContext.set(PRISMA_CLIENT_KEY, null);\n            throw err;\n          }\n        });\n      });\n    }\n  }\n}\n```","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkenfdev%2Fprisma-auto-transaction-poc","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkenfdev%2Fprisma-auto-transaction-poc","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkenfdev%2Fprisma-auto-transaction-poc/lists"}