`client`:向 Prisma 客户端添加方法
Prisma 客户端扩展从版本 4.16.0 及更高版本开始正式可用。它们是在 4.7.0 版本的预览版中引入的。如果你运行的版本早于 4.16.0,请确保启用 clientExtensions
Preview 功能标志。
¥Prisma Client extensions are Generally Available from versions 4.16.0 and later. They were introduced in Preview in version 4.7.0. Make sure you enable the clientExtensions
Preview feature flag if you are running on a version earlier than 4.16.0.
你可以使用 client
Prisma 客户端扩展 组件将顶层方法添加到 Prisma 客户端。
¥You can use the client
Prisma Client extensions component to add top-level methods to Prisma Client.
扩展 Prisma 客户端
¥Extend Prisma Client
使用 $extends
客户级方法 创建扩展客户端。扩展客户端是标准 Prisma 客户端的一种变体,由一个或多个扩展封装。使用 client
扩展组件向 Prisma 客户端添加顶层方法。
¥Use the $extends
client-level method to create an extended client. An extended client is a variant of the standard Prisma Client that is wrapped by one or more extensions. Use the client
extension component to add top-level methods to Prisma Client.
要将顶层方法添加到 Prisma Client,请使用以下结构:
¥To add a top-level method to Prisma Client, use the following structure:
const prisma = new PrismaClient().$extends({
client?: { ... }
})
示例
¥Example
以下示例使用 client
组件向 Prisma Client 添加两个方法:
¥The following example uses the client
component to add two methods to Prisma Client:
-
$log
输出一条消息。¥
$log
outputs a message. -
$totalQueries
返回当前客户端实例执行的查询数。它使用 metrics 功能来收集此信息。¥
$totalQueries
returns the number of queries executed by the current client instance. It uses the metrics feature to collect this information.
要在项目中使用指标,你必须在 schema.prisma
文件的 generator
块中启用 metrics
功能标志。了解更多。
¥To use metrics in your project, you must enable the metrics
feature flag in the generator
block of your schema.prisma
file. Learn more.
const prisma = new PrismaClient().$extends({
client: {
$log: (s: string) => console.log(s),
async $totalQueries() {
const index_prisma_client_queries_total = 0
// Prisma.getExtensionContext(this) in the following block
// returns the current client instance
const metricsCounters = await (
await Prisma.getExtensionContext(this).$metrics.json()
).counters
return metricsCounters[index_prisma_client_queries_total].value
},
},
})
async function main() {
prisma.$log('Hello world')
const totalQueries = await prisma.$totalQueries()
console.log(totalQueries)
}