npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@myfunc/prisma-transactional

v0.3.0

Published

Decorator that wraps all prisma queries along the whole call stack to a single transaction.

Downloads

21

Readme

@myfunc/prisma-transactional

Package contains @PrismaTransactional decorator that wraps all prisma queries along the whole call stack to a single transaction. In case of overlapping several transactions they will be merged.

Use in production at your own risk. A decorator is being actively used on production environment with no issues, but I strictly recommend to wait for a stable release.

Installation

npm i @myfunc/prisma-transactional

Universal setup in node.js application

import { PrismaClient } from '@prisma/client';
import { patchPrismaTx } from '@myfunc/prisma-transactional';

const prisma = patchPrismaTx(new PrismaClient());

How to setup in NestJS application

Patch your PrismaClient with patchPrismaTx(client, config)

import { patchPrismaTx } from '@myfunc/prisma-transactional';
import { Injectable, OnModuleInit } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';

@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
  constructor() {
    super();
    return patchPrismaTx(this);
  }

  async onModuleInit() {
    await this.$connect();
  }
}

Now you can use PrismaTransactional.

Run example

In Example application described all possible decorator's use cases. For running example app, please edit DB connection string in the .env file.

npm i
npm run dev

How to use the decorator

You can add decorator to any class-method. All queries inside will be wrapped in a single transaction.

On any unhandled error all changed will be rolled back.

BE CAREFUL when using it, all queries inside transaction will be isolated and can lead to deadlock.

Example

export class BalanceService { 
  constructor(private prisma: PrismaService) {}

  // Now all queries (including nested queries in methods) will be executed in transaction
  @PrismaTransactional() 
  async addPoints(userId: string, amount: number) {
    const { balance } = await this.getBalance(userId);
    const newBalance = await this.prisma.user.update({
      select: {
        balance: true,
      },
      where: { id: userId },
      data: { balance: roundBalance(balance + amount) },
    });
    return {
      newBalance
    };
  }

  async getBalance(userId: string) {
    // Query will be wrapped in transaction if called by addPoints() method.
    const { balance } = await this.prisma.user.findUnique({
        where: {
            id: userId
        },
        select: {
            balance: true
        }
    });
    return balance;
  }
}

To handle success commit you can put the following code anywhere in the code. If there is no transaction, a callback will be executed immediately.

PrismaTransactional.onSuccess(() => {
  this.notifyBalanceUpdated(balance!, args._notificationDelay);
});

Also, you can add many callbacks. All callbacks are stored in a stack under the hood.

You can execute all in transaction with no decorator.

await PrismaTransactional.execute(async () => {
  await this.prisma.users.findMany({});
  await this.prisma.users.deleteMany({});
});

Or return a result from a success execution.

const result = await PrismaTransactional.execute(async () => {
  const result = await this.prisma.users.findMany({});
  await this.prisma.users.deleteMany({});
  return result;
});

Execute a query out of current transaction context.

@PrismaTransactional() 
  async addPoints(userId: string, amount: number) {
    const { balance } = await this.getBalance(userId);

    // userLog item will be created even if current transaction will be rolled back.
    await PrismaTransactional.prismaRoot.userLog.create(
      { 
        note: `Attempt to add balance for user ${userId} with balance ${balance}`
      }
    );

    const newBalance = await this.prisma.user.update({
      select: {
        balance: true,
      },
      where: { id: userId },
      data: { balance: roundBalance(balance + amount) },
    });
    return {
      newBalance
    };
  }

Plans

  • [x] Add PrismaTransactional.prismaRoot method for running queries out of transaction context.
  • [ ] Add tests.
  • [x] Add express.js example.
  • [ ] Add nestjs example.
  • [ ] Get rid of hardcoded values and make them configurable. "TRANSACTION_TIMEOUT"
  • [ ] Safety improvements. As an idea - implement ESLint rule for nested prisma queries that might be unintentionally executed in transaction. That means a developer will be aknowledged about possible transaction wrapping and force him to add an eslint-ignore comment.
  • [ ] Clean code.