类型工具
Prisma Client 中存在多种类型工具,可帮助创建高度类型安全的扩展。
类型工具
Prisma Client 类型工具是应用程序和 Prisma Client 扩展中可用的工具,提供了构建安全且可扩展类型的方法,以便用于你的扩展。
可用的类型工具有
- `Exact<Input, Shape>`:对 `Input` 强制执行严格的类型安全。`Exact` 确保泛型类型 `Input` 严格符合你在 `Shape` 中指定的类型。它将 `Input` 缩窄到最精确的类型。
- `Args<Type, Operation>`:检索给定模型和操作的输入参数。这对于希望执行以下操作的扩展作者特别有用
- 复用现有类型以扩展或修改它们。
- 从与现有操作相同的自动补全体验中受益。
- `Result<Type, Arguments, Operation>`:接受输入参数并为给定模型和操作提供结果。你通常会结合 `Args` 使用它。与 `Args` 类似,`Result` 帮助你复用现有类型以扩展或修改它们。
- `Payload<Type, Operation>`:检索结果的整个结构,包括给定模型和操作的标量和关系对象。例如,你可以使用它来在类型层面确定哪些键是标量或对象。
以下示例基于 `findFirst` 创建了一个新操作 `exists`。它拥有 `findFirst` 的所有参数。
const prisma = new PrismaClient().$extends({
model: {
$allModels: {
// Define a new `exists` operation on all models
// T is a generic type that corresponds to the current model
async exists<T>(
// `this` refers to the current type, e.g. `prisma.user` at runtime
this: T,
// The `exists` function will use the `where` arguments from the current model, `T`, and the `findFirst` operation
where: Prisma.Args<T, 'findFirst'>['where']
): Promise<boolean> {
// Retrieve the current model at runtime
const context = Prisma.getExtensionContext(this)
// Prisma Client query that retrieves data based
const result = await (context as any).findFirst({ where })
return result !== null
},
},
},
})
async function main() {
const user = await prisma.user.exists({ name: 'Alice' })
const post = await prisma.post.exists({
OR: [
{ title: { contains: 'Prisma' } },
{ content: { contains: 'Prisma' } },
],
})
}
为方法添加自定义属性
以下示例说明了如何在扩展中为方法添加自定义参数
type CacheStrategy = {
swr: number
ttl: number
}
const prisma = new PrismaClient().$extends({
model: {
$allModels: {
findMany<T, A>(
this: T,
args: Prisma.Exact<
A,
// For the `findMany` method, use the arguments from model `T` and the `findMany` method
// and intersect it with `CacheStrategy` as part of `findMany` arguments
Prisma.Args<T, 'findMany'> & CacheStrategy
>
): Prisma.Result<T, A, 'findMany'> {
// method implementation with the cache strategy
},
},
},
})
async function main() {
await prisma.post.findMany({
cacheStrategy: {
ttl: 360,
swr: 60,
},
})
}
此处的示例仅是概念性的。要使实际的缓存工作,你需要实现其逻辑。如果你对缓存扩展/服务感兴趣,我们建议查看 Prisma Accelerate。