Skip to content

Commit c8b5196

Browse files
docs: add middleware chaining example (#7437)
1 parent 38c1be1 commit c8b5196

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

  • content/200-orm/200-prisma-client/300-client-extensions

content/200-orm/200-prisma-client/300-client-extensions/index.mdx

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,42 @@ In your code, you can call any of these clients separately, for example `prismaA
162162

163163
When you combine two or more extensions into a single extended client, then the _last_ extension that you declare takes precedence in any conflict. In the example in option 1 above, suppose there is a method called `myExtensionMethod()` defined in `extensionA` and a method called `myExtensionMethod()` in `extensionB`. When you call `prismaAB.myExtensionMethod()`, then Prisma Client uses `myExtensionMethod()` as defined in `extensionB`.
164164

165+
### Middleware chaining with query extensions
166+
167+
Chain [`query`](/orm/prisma-client/client-extensions/query) extensions to compose middleware. Extensions execute in order—first in, first out:
168+
169+
```ts
170+
import { PrismaClient } from './generated/prisma'
171+
172+
const prisma = new PrismaClient()
173+
// Extension 1: Logging - measures query execution time
174+
.$extends({
175+
query: {
176+
$allModels: {
177+
async $allOperations({ model, operation, args, query }) {
178+
const start = Date.now()
179+
const result = await query(args)
180+
console.log(`[LOGGING] ${model}.${operation}: ${Date.now() - start}ms`)
181+
return result
182+
},
183+
},
184+
},
185+
})
186+
// Extension 2: Audit - logs write operations
187+
.$extends({
188+
query: {
189+
$allModels: {
190+
async $allOperations({ model, operation, args, query }) {
191+
if (['create', 'update', 'delete'].includes(operation)) {
192+
console.log(`[AUDIT] ${operation} on ${model}:`, JSON.stringify(args))
193+
}
194+
return query(args)
195+
},
196+
},
197+
},
198+
})
199+
```
200+
165201
## Type of an extended client
166202

167203
You can infer the type of an extended Prisma Client instance using the [`typeof`](https://www.typescriptlang.org/docs/handbook/2/typeof-types.html) utility as follows:

0 commit comments

Comments
 (0)