跳到主要內容

類型工具

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