Theo's Typesafe CultTTC
Theo's Typesafe Cult3y ago
1 reply
domi?

Prisma middleware infinite loop

Hey 👋

I have a separate table in my db that's responsible for storing logs of actions.

I want to simplify the dx by creating a Prisma middleware that will automatically create these logs.

This is my current implementation:
prisma.$use(async (params, next) => {
    const { model, action } = params;

    if (model === 'Todo' && (action === 'create')) {
        await prisma.logEntry.create({
            data: {
                type: 'CREATED_TODO',
                user: {
                    connect: {
                        id: params.args.data.userId
                    }
                }
            }
        });
    }

    return next(params);
});


However, I'd like to improve this to be batching these db calls into one prisma.$transaction():
const result = await prisma.$transaction([
    prisma.todo.create(params.args),
    prisma.logEntry.create({
        data: {
            type: 'CREATED_TODO',
            user: {
                connect: {
                    id: params.args.data.userId
                }
            }
        }
    })
]);

However, this causes an infinite loop, because prisma.todo.create() calls the middleawre again.

Any suggestions on how to get around this?
Was this page helpful?