Pass Prisma transaction into a function in typescript
Asked Answered
R

3

7

Hi I have following issue. I have prisma transaction but I would like to pass the prisma transaction client into a function like this:

...
prisma.$transaction(async (tx) => {
  someFunction(tx)
})
...

function someFunction(tx: WHATTOTYPEHERE){
}

However I am doing it in typescript and I don't want to use type ANY. But i dont know how to type the interactive transactin prisma client... the "WHATTOTYPEHERE" type for it.

Any help is appreciated

Rb answered 1/10, 2023 at 9:23 Comment(0)
Q
6

The type in the (EDIT: formerly) accepted answer is no longer correct in the latest version of Prisma.

As a more future-proof type, you can use the Parameters type helper to extract the type from the $transaction method itself.

This will work even if the transaction type changes as long as the $transaction's method signature stays the same.

import { PrismaClient } from "@prisma/client";

export type PrismaTransactionalClient = Parameters<
    Parameters<PrismaClient['$transaction']>[0]
>[0];
Quackery answered 22/1 at 10:56 Comment(0)
S
4

this code is also work and this is the 1st way

import { PrismaClient } from "@prisma/client";

export type PrismaTransactionalClient = Parameters<
    Parameters<PrismaClient['$transaction']>[0]
>[0];

but there is a 2nd way and this is the official way

import { Prisma } from "@prisma/client";

export type PrismaTransactionalClient = Prisma.TransactionClient;
Scamper answered 27/5 at 12:40 Comment(0)
Z
3

If you peeked the definition of $transaction, you would find this:

$transaction<R>(fn: (prisma: Omit<this, "$connect" | "$disconnect" | "$on" | "$transaction" | "$use">) => Promise<R>, options?: { maxWait?: number, timeout?: number }): Promise<R>

Copy/paste that definition and write your own type for use:

import { PrismaClient } from "@prisma/client";

type PrismaTransactionClient = Omit<PrismaClient, "$connect" | "$disconnect" | "$on" | "$transaction" | "$use">

function someFunction(tx: PrismaTransactionClient){
// code here
} 
Zia answered 12/10, 2023 at 20:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.