Computed fields
Computed fieldsを使用すると、既存のデータに基づいて新しいフィールドを導出できます。一般的な例は、フルネームを計算する場合です。データベースには、名と姓のみが保存されている場合がありますが、名と姓を組み合わせてフルネームを計算する関数を定義できます。Computed fieldsは読み取り専用であり、データベースではなくアプリケーションのメモリに保存されます。
Prisma Client拡張機能の使用
次の例は、PrismaスキーマのUser
モデルにランタイム時にfullName
computed fieldを追加するPrisma Client拡張機能を作成する方法を示しています。
- Prisma Client拡張機能
- Prismaスキーマ
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()
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model User {
id Int @id @default(autoincrement())
email String @unique
firstName String
lastName String
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
title String
published Boolean @default(true)
content String?
authorId Int?
author User? @relation(fields: [authorId], references: [id])
}
computed fieldsは型安全であり、連結された値から複雑なオブジェクト、またはモデルのインスタンスメソッドとして機能できる関数まで、あらゆるものを返すことができます。
Prisma ORM 4.16.0より前の手順
Prisma Client拡張機能はPrisma ORMバージョン4.16.0以降で一般提供されているため、以下の手順は推奨されません。これを行うには、クライアント拡張機能を使用してください。
Prisma Clientはまだcomputed fieldsをネイティブにサポートしていませんが、ジェネリック型を入力として受け入れ、そのジェネリックを拡張して特定の構造に準拠させる関数を定義できます。最後に、追加のcomputed fieldsを持つジェネリックを返すことができます。それがどのように見えるか見てみましょう。
- TypeScript
- JavaScript
// 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)
}
function computeFullName(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に賛成票を投じ、ユースケースを共有してください!