Prisma 验证器
Prisma.validator
是一个实用程序函数,它接受生成的类型并返回遵循生成的类型模型字段的类型安全对象。
¥The Prisma.validator
is a utility function that takes a generated type and returns a type-safe object which adheres to the generated types model fields.
本页介绍了 Prisma.validator
并提供了你可能选择使用它的一些动机。
¥This page introduces the Prisma.validator
and offers some motivations behind why you might choose to use it.
注意:如果你有
Prisma.validator
的用例,请务必查看有关使用新的 TypeScriptsatisfies
关键字改进 Prisma Client 工作流程的 博客文章。你很可能可以使用satisfies
而不是使用Prisma.validator
来本地解决你的用例。¥Note: If you have a use case for
Prisma.validator
, be sure to check out this blog post about improving your Prisma Client workflows with the new TypeScriptsatisfies
keyword. It's likely that you can solve your use case natively usingsatisfies
instead of usingPrisma.validator
.
创建类型化查询语句
¥Creating a typed query statement
假设你创建了一个新的 userEmail
对象,希望在整个应用的不同查询中重复使用该对象。它是键入的并且可以在查询中安全地使用。
¥Let's imagine that you created a new userEmail
object that you wanted to re-use in different queries throughout your application. It's typed and can be safely used in queries.
下面的例子要求 Prisma
返回 id
为 3 的用户的 email
,如果不存在则返回 null
。
¥The below example asks Prisma
to return the email
of the user whose id
is 3, if no user exists it will return null
.
import { Prisma } from '@prisma/client'
const userEmail: Prisma.UserSelect = {
email: true,
}
// Run inside async function
const user = await prisma.user.findUnique({
where: {
id: 3,
},
select: userEmail,
})
这很有效,但以这种方式提取查询语句有一个警告。
¥This works well but there is a caveat to extracting query statements this way.
你会注意到,如果将鼠标悬停在 userEmail
上,TypeScript 将不会推断对象的键或值(即 email: true
)。
¥You'll notice that if you hover your mouse over userEmail
TypeScript won't infer the object's key or value (that is, email: true
).
如果你在 prisma.user.findUnique(...)
查询中对 userEmail
使用点表示法,则同样适用,你将能够访问 select
对象可用的所有属性。
¥The same applies if you use dot notation on userEmail
within the prisma.user.findUnique(...)
query, you will be able to access all of the properties available to a select
object.
如果你在一个文件中使用它可能没问题,但如果你要导出该对象并在其他查询中使用它,或者如果你正在编译一个外部库,你希望在其中控制用户在查询中如何使用该对象,那么这将不是类型安全的。
¥If you are using this in one file that may be fine, but if you are going to export this object and use it in other queries, or if you are compiling an external library where you want to control how the user uses this object within their queries then this won't be type-safe.
对象 userEmail
已创建为仅选择用户的 email
,但它仍然允许访问所有其他可用属性。它是类型化的,但不是类型安全的。
¥The object userEmail
has been created to select only the user's email
, and yet it still gives access to all the other properties available. It is typed, but not type-safe.
Prisma
有一种方法来验证生成的类型以确保它们是类型安全的,这是名为 validator
的命名空间上可用的实用程序函数。
¥Prisma
has a way to validate generated types to make sure they are type-safe, a utility function available on the namespace called validator
.
使用 Prisma.validator
¥Using the Prisma.validator
以下示例将 UserSelect
生成的类型传递到 Prisma.validator
实用程序函数中,并以与前面的示例大致相同的方式定义预期返回类型。
¥The following example passes the UserSelect
generated type into the Prisma.validator
utility function and defines the expected return type in much the same way as the previous example.
import { Prisma } from '@prisma/client'
const userEmail: Prisma.UserSelect = {
email: true,
}
const userEmail = Prisma.validator<Prisma.UserSelect>()({
email: true,
})
// Run inside async function
const user = await prisma.user.findUnique({
where: {
id: 3,
},
select: userEmail,
})
或者,你可以使用以下语法,该语法使用 Prisma Client 的现有实例使用 "selector" 模式:
¥Alternatively, you can use the following syntax that uses a "selector" pattern using an existing instance of Prisma Client:
import { Prisma } from '@prisma/client'
import prisma from './lib/prisma'
const userEmail = Prisma.validator(
prisma,
'user',
'findUnique',
'select'
)({
email: true,
})
最大的区别是 userEmail
对象现在是类型安全的。如果将鼠标悬停在其上,TypeScript 会告诉你该对象的键/值对。如果使用点表示法访问对象的属性,你将只能访问对象的 email
属性。
¥The big difference is that the userEmail
object is now type-safe. If you hover your mouse over it TypeScript will tell you the object's key/value pair. If you use dot notation to access the object's properties you will only be able to access the email
property of the object.
当与用户定义的输入(例如表单数据)结合使用时,此功能非常方便。
¥This functionality is handy when combined with user defined input, like form data.
将 Prisma.validator
与表单输入相结合
¥Combining Prisma.validator
with form input
以下示例从 Prisma.validator
创建类型安全函数,可在与用户创建的数据(例如表单输入)交互时使用。
¥The following example creates a type-safe function from the Prisma.validator
which can be used when interacting with user created data, such as form inputs.
注意:表单输入是在运行时确定的,因此无法仅使用 TypeScript 进行验证。在将数据传递到数据库之前,请务必通过其他方式(例如外部验证库)验证表单输入。
¥Note: Form input is determined at runtime so can't be verified by only using TypeScript. Be sure to validate your form input through other means too (such as an external validation library) before passing that data through to your database.
import { Prisma, PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
// Create a new function and pass the parameters onto the validator
const createUserAndPost = (
name: string,
email: string,
postTitle: string,
profileBio: string
) => {
return Prisma.validator<Prisma.UserCreateInput>()({
name,
email,
posts: {
create: {
title: postTitle,
},
},
profile: {
create: {
bio: profileBio,
},
},
})
}
const findSpecificUser = (email: string) => {
return Prisma.validator<Prisma.UserWhereInput>()({
email,
})
}
// Create the user in the database based on form input
// Run inside async function
await prisma.user.create({
data: createUserAndPost(
'Rich',
'rich@boop.com',
'Life of Pie',
'Learning each day'
),
})
// Find the specific user based on form input
// Run inside async function
const oneUser = await prisma.user.findUnique({
where: findSpecificUser('rich@boop.com'),
})
createUserAndPost
自定义函数是使用 Prisma.validator
创建的,并传递生成的类型 UserCreateInput
。Prisma.validator
验证函数输入,因为分配给参数的类型必须与生成的类型期望的类型匹配。
¥The createUserAndPost
custom function is created using the Prisma.validator
and passed a generated type, UserCreateInput
. The Prisma.validator
validates the functions input because the types assigned to the parameters must match those the generated type expects.