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

Computed fields

Computed fieldsを使用すると、既存のデータに基づいて新しいフィールドを導出できます。一般的な例は、フルネームを計算する場合です。データベースには、名と姓のみが保存されている場合がありますが、名と姓を組み合わせてフルネームを計算する関数を定義できます。Computed fieldsは読み取り専用であり、データベースではなくアプリケーションのメモリに保存されます。

Prisma Client拡張機能の使用

次の例は、PrismaスキーマのUserモデルにランタイム時にfullName computed fieldを追加するPrisma Client拡張機能を作成する方法を示しています。

import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient().$extends({
result: {
user: {
fullName: {
needs: { firstName: true, lastName: true },
compute(user) {
return `${user.firstName} ${user.lastName}`
},
},
},
},
})

async function main() {
/**
* Example query containing the `fullName` computed field in the response
*/
const user = await prisma.user.findFirst()
}

main()
表示CLI結果

computed fieldsは型安全であり、連結された値から複雑なオブジェクト、またはモデルのインスタンスメソッドとして機能できる関数まで、あらゆるものを返すことができます。

Prisma ORM 4.16.0より前の手順
warning

Prisma Client拡張機能はPrisma ORMバージョン4.16.0以降で一般提供されているため、以下の手順は推奨されません。これを行うには、クライアント拡張機能を使用してください。

Prisma Clientはまだcomputed fieldsをネイティブにサポートしていませんが、ジェネリック型を入力として受け入れ、そのジェネリックを拡張して特定の構造に準拠させる関数を定義できます。最後に、追加のcomputed fieldsを持つジェネリックを返すことができます。それがどのように見えるか見てみましょう。

// Define a type that needs a first and last name
type FirstLastName = {
firstName: string
lastName: string
}

// Extend the T generic with the fullName attribute
type WithFullName<T> = T & {
fullName: string
}

// Take objects that satisfy FirstLastName and computes a full name
function computeFullName<User extends FirstLastName>(
user: User
): WithFullName<User> {
return {
...user,
fullName: user.firstName + ' ' + user.lastName,
}
}

async function main() {
const user = await prisma.user.findUnique({ where: 1 })
const userWithFullName = computeFullName(user)
}

上記のTypeScriptの例では、FirstLastName型を拡張するUserジェネリックが定義されています。これは、computeFullNameに渡すものは何でもfirstNameキーとlastNameキーを含める必要があることを意味します。

WithFullName<User>戻り値の型も定義されており、Userが何であれ、fullName文字列属性を追加します。

この関数を使用すると、firstNameキーとlastNameキーを含む任意のオブジェクトがfullNameを計算できます。かなり便利ですよね?

さらに進む

  • Prisma Client拡張機能を使用して、computed fieldをスキーマに追加する方法を学びましょう—
  • computeFullName関数をカスタムモデルに移動する方法を学びましょう。
  • Prisma Clientにネイティブサポートを追加するためのオープンな機能リクエストがあります。それが実現するのを見たい場合は、そのissueに賛成票を投じ、ユースケースを共有してください!