
Zod 是一个流行的 TypeScript 优先的模式声明和验证库。在使用 Zod 验证数据时,默认行为是严格的:只有在模式中明确定义的字段才会被保留,其他字段会被过滤掉。然而,在某些情况下,我们希望只验证数据的子集,而保留其他未指定的字段。这时,.passthrough() 方法就派上用场了。
正如本文摘要所述,Zod 默认会过滤掉模式中未明确指定的字段。例如,以下代码定义了一个只验证 params 对象中 dependent_id 字段的模式:
import { z } from 'zod';
const schema = z.object({
params: z.object({ dependent_id: z.string() }),
})
const req = {
params: { dependent_id: "blah", bar: "baz" },
body: { foo: "bar" },
query: {}
}
const test = async () => {
const { params, body, query } = await schema.parseAsync(req);
console.log("params: ", params)
console.log("body: ", body)
console.log("query: ", query)
}
test()这段代码的输出如下:
params: { dependent_id: 'blah' }
body: undefined
query: undefined可以看到,params 对象中除了 dependent_id 之外的 bar 字段被过滤掉了,body 和 query 也因为没有在 schema 中定义所以输出为 undefined。为了解决这个问题,可以使用 .passthrough() 方法。
.passthrough() 方法会使 Zod 忽略未知的键,并将它们保留在输出中。要使用 .passthrough(),只需在模式上调用该方法即可:
import { z } from 'zod';
const schema = z.object({
params: z.object({ dependent_id: z.string() }),
})
const req = {
params: { dependent_id: "blah", bar: "baz" },
body: { foo: "bar" },
query: {}
}
const test = async () => {
const { params, body, query } = await schema.passthrough().parseAsync(req);
console.log("params: ", params)
console.log("body: ", body)
console.log("query: ", query)
}
test()现在,输出将会是:
params: { dependent_id: 'blah', bar: 'baz' }
body: { foo: 'bar' }
query: {}可以看到,params 对象中的 bar 字段、body 和 query 都被保留了下来。
通过使用 .passthrough() 方法,我们可以轻松地在 Zod 模式中允许未指定字段的透传。这在需要验证数据子集,同时保留其他未经验证的字段时非常有用。然而,在使用 .passthrough() 方法时,需要注意数据的安全性,并确保未经验证的字段不会对应用程序造成安全风险。
以上就是Zod 模式中允许未指定字段透传的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号