P
Prisma6mo ago
ptrxyz

About transactions and extensions

I want to add custom methods to my model:
export default Prisma.defineExtension((c) =>
return {
model: {
user: {
doCreate: async (name: string) => {
return await c.user.create({ data: { name } });
},
},
}
}
})
export default Prisma.defineExtension((c) =>
return {
model: {
user: {
doCreate: async (name: string) => {
return await c.user.create({ data: { name } });
},
},
}
}
})
This doesn't seem to work when I call the method inside a transaction. I found this: https://www.prisma.io/docs/orm/prisma-client/client-extensions/shared-extensions#call-a-client-level-method-from-your-packaged-extension Does this apply here? Or am I doing it wrong?
3 Replies
Prisma AI Help
Prisma AI Help6mo ago
You decided to hold for human wisdom. We'll chime in soon! Meanwhile, #ask-ai is there if you need a quick second opinion.
ptrxyz
ptrxyzOP6mo ago
Ok, i have a better example:
const prisma = new PrismaClient();
const xprisma = prisma.$extends({
model: {
user: {
doCreate: async (name: string) => {
return await xprisma.user.create({ data: { name } });
},
},
},
});

await xprisma.$transaction(async (tx) => {
await tx.user.doCreate("johndoe");
throw new Error("Rollback");
});
const prisma = new PrismaClient();
const xprisma = prisma.$extends({
model: {
user: {
doCreate: async (name: string) => {
return await xprisma.user.create({ data: { name } });
},
},
},
});

await xprisma.$transaction(async (tx) => {
await tx.user.doCreate("johndoe");
throw new Error("Rollback");
});
This example seems to fail, i suppose beacuse I am referencing xprisma directly? But if I go with the closure-style extension Prisma.defineExtension((c) => { ... }) I am running into the problem the warning in the docs is about. Can someone shed some light on this? What am I doing wrong, and how can i attach a transaction-safe custom method to my model?
Nurul
Nurul6mo ago
When you say the example fails, you mean that the user is still created even if you rollback, correct? Currently there is a limitation that if you trigger the extension from inside a transaction (interactive or batched), the extension code will issue the queries in a new connection and ignore the current transaction context.

Did you find this page helpful?