Configuration

Configuration

The extension is configured by being added to your Prisma Client instance. This requires two main steps: updating your schema and creating an extended Prisma Client.

First, update your prisma/schema.prisma file. You need to add the AuditLog model that the extension will use to store the log entries. We also include a placeholder User model to make the relation valid.

// A placeholder User model for the relation in AuditLog
model User {
  id        String     @id @default(uuid())
  email     String     @unique
  name      String?
  auditLogs AuditLog[]
}

// The AuditLog model is required by the extension
model AuditLog {
    id String @id @default(uuid())

    model 	  String
    operation String

    data Json?

    createdAt DateTime @default(now())
    updatedAt DateTime @updatedAt

    user      User?    @relation(fields: [userId], references: [id])
    userId    String?
}

NestJS Integration with nestjs-cls

For applications built with NestJS, you can leverage the nestjs-cls package to automatically retrieve the userId from the request context and pass it to the extension.

First, install the nestjs-cls package:

Then, configure a PrismaModule with a factory provider that creates the extended Prisma Client. This method is the recommended way to integrate the ClsService as it allows you to pass the service directly to the extension. The auditLog extension will then use the ClsService to get the userId from the request context automatically.

Then, add ClsPluginPrismaAuditLog plugin to the ClsModle and provide the function to retrieve the user from the request, here is an example

And Done!

Usage

Once configured, the extension works transparently in the background. You can perform standard Prisma Client operations, and the extension will automatically handle the logging.

Here is an example of a simple CRUD operation. The AuditLog model will be automatically updated after each create, update, and delete call. The data field will contain a JSON object of the changes.

Last updated