P
Prisma•6d ago
NeekoNeeko

If I extend create, is there a way to extend createMany as well?

Hi, I'm looking to extend the create method for one of my Models, but is there a way to simultaneously extend createMany? I asked the AI and it said that I'd have to manually update both, but would extending createMany to call create under the hood be a reasonable approach or would it be bad for some reason?
6 Replies
Prisma AI Help
Prisma AI Help•6d ago
You chose to debug with a human. They'll tinker with your query soon. If you get curious meanwhile, hop into #ask-ai for a quick spin!
NeekoNeeko
NeekoNeekoOP•6d ago
Additionally I'd prefer to not have to modify create, createMany and createManyAndReturn if possible
Nurul
Nurul•6d ago
Hey 👋 What is your use case? Is there any specific reason why you want to extend createMany to internally invoke create? createMany uses transactions internally to ensure atomicity.
NeekoNeeko
NeekoNeekoOP•6d ago
Hi! So the use case is that whenever someone makes a write update to a model (call it User), we want to add a row to another table (call it UserLog) to log that change, i.e., the UserLog would be something like "User X was UPDATED with these changes at 4:45pm"
Nurul
Nurul•6d ago
Thanks for sharing your usecase. In your case, I think you would need to extend create and createMany operations both. https://www.prisma.io/docs/orm/prisma-client/client-extensions/query#modify-a-specific-operation-in-a-specific-model You would want to modify create and createMany operations. Something like this:
const prisma = new PrismaClient().$extends({
query: {
user: {
async create({ args, query }) {
const result = await query(args);
await prisma.userLog.create({
data: {
action: 'CREATE',
userId: result.id,
changes: JSON.stringify(args.data),
timestamp: new Date(),
},
});
return result;
},
async createMany({ args, query }) {
const result = await query(args);
await prisma.userLog.createMany({
data: args.data.map(userData => ({
action: 'CREATE',
userId: userData.id, // Assuming id is part of the data
changes: JSON.stringify(userData),
timestamp: new Date(),
})),
});
return result;
},
},
},
});
const prisma = new PrismaClient().$extends({
query: {
user: {
async create({ args, query }) {
const result = await query(args);
await prisma.userLog.create({
data: {
action: 'CREATE',
userId: result.id,
changes: JSON.stringify(args.data),
timestamp: new Date(),
},
});
return result;
},
async createMany({ args, query }) {
const result = await query(args);
await prisma.userLog.createMany({
data: args.data.map(userData => ({
action: 'CREATE',
userId: userData.id, // Assuming id is part of the data
changes: JSON.stringify(userData),
timestamp: new Date(),
})),
});
return result;
},
},
},
});
Prisma Client extensions: query component | Prisma Documentation
Extend the functionality of Prisma Client, query component
NeekoNeeko
NeekoNeekoOP•6d ago
Okay, thank you!

Did you find this page helpful?