跳到主要內容

型別工具

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

© . This site is unofficial and not affiliated with Prisma Data, Inc.