Skip to content

Commit

Permalink
chore(db): add logger to mutations
Browse files Browse the repository at this point in the history
  • Loading branch information
lindesvard committed Feb 22, 2025
1 parent bc311e3 commit 93944fe
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 8 deletions.
35 changes: 29 additions & 6 deletions packages/db/src/prisma-client.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,39 @@
import { createLogger } from '@openpanel/logger';
import { PrismaClient } from '@prisma/client';
import { readReplicas } from '@prisma/extension-read-replicas';

export * from '@prisma/client';

const logger = createLogger({ name: 'db' });

const getPrismaClient = () => {
return new PrismaClient({
const prisma = new PrismaClient({
log: ['error'],
}).$extends(
readReplicas({
url: process.env.DATABASE_URL_REPLICA ?? process.env.DATABASE_URL!,
}),
);
})
.$extends(
readReplicas({
url: process.env.DATABASE_URL_REPLICA ?? process.env.DATABASE_URL!,
}),
)
.$extends({
query: {
async $allOperations({ operation, model, args, query }) {
if (
operation === 'create' ||
operation === 'update' ||
operation === 'delete'
) {
logger.info('Prisma operation', {
operation,
args,
});
}
return query(args);
},
},
});

return prisma;
};

const globalForPrisma = globalThis as unknown as {
Expand Down
24 changes: 22 additions & 2 deletions packages/trpc/src/trpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,27 @@ const enforceAccess = t.middleware(async ({ ctx, next, rawInput }) => {

export const createTRPCRouter = t.router;

export const publicProcedure = t.procedure;
const loggerMiddleware = t.middleware(
async ({ ctx, next, rawInput, path, input, type }) => {
// Only log mutations
if (type === 'mutation') {
ctx.req.log.info('TRPC mutation', {
path,
rawInput,
input,
userId: ctx.session?.userId,
organizationId: has('organizationId', rawInput)
? rawInput.organizationId
: undefined,
projectId: has('projectId', rawInput) ? rawInput.projectId : undefined,
});
}
return next();
},
);

export const publicProcedure = t.procedure.use(loggerMiddleware);
export const protectedProcedure = t.procedure
.use(enforceUserIsAuthed)
.use(enforceAccess);
.use(enforceAccess)
.use(loggerMiddleware);

0 comments on commit 93944fe

Please sign in to comment.