メインコンテンツにスキップ

型ユーティリティ

Prisma Client内には、高度にタイプセーフな拡張機能の作成を支援できるいくつかの型ユーティリティが存在します。

型ユーティリティ

Prisma Client型ユーティリティは、アプリケーションとPrisma Client拡張機能内で利用可能なユーティリティであり、拡張機能の安全で拡張可能な型を構築するのに役立つ方法を提供します。

利用可能な型ユーティリティは次のとおりです

  • Exact<Input, Shape>: Inputに厳密な型安全性を適用します。Exactは、ジェネリック型InputShapeで指定した型に厳密に準拠していることを確認します。それは絞り込み 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をご覧ください。