型ユーティリティ
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をご覧いただくことをお勧めします。