我想知道是否有一种简单的方法可以在 Javascript 中验证对象的形状。
现在,我有一个函数可以验证端点对象的形状,如下所示:
function validateEndpointShape(endpoint: any, hasId: boolean): boolean
{
return endpoint
&& (hasId ? typeof endpoint.id === 'string' : true)
&& typeof endpoint.name === 'string'
&& typeof endpoint.description === 'string'
&& typeof endpoint.url === 'string'
&& GenericApiEndpointMethods[endpoint.method] !== undefined
&& ApiEndpointTypes[endpoint.apiEndpointType] !== undefined
&& endpoint.group
&& typeof endpoint.group.groupPublicKey === 'string'
&& typeof endpoint.group.groupName === 'string'
&& typeof endpoint.reason === 'string'
&& typeof endpoint.isPublic === 'boolean'
&& typeof endpoint.isActive === 'boolean'
&& authTypes[endpoint.authType] !== undefined
&& Array.isArray(endpoint.parameters)
&& Array.isArray(endpoint.headers);
}
这可能会变得麻烦且难以操作。我不想为我创建的每个对象都执行此操作。
当端点进入我们的云 Firebase 函数时,我们必须对其进行大量验证,以便我们知道何时拒绝不良数据。端点的形状就是这些验证之一。
我尝试这样做:
Delete req.body.reason;
req.body[‘extraField’] = ‘xxx’;
Const endpoint: GenericApiEndpoint = req.body;
console.log(‘endpoint =‘, endpoint);
但是 Javascript 并不关心。它将接受没有原因的端点(强制字段)和带有 extraField(模型中不存在的字段)的端点,并将其分配给类型为 GenericApiEndpoint 的对象。端点无故打印并带有额外字段。
我也尝试过:
Const endpoint = <GenericApiEndpoint>req.body;
…但 Javascript 也不关心这一点。
有人知道在 Javascript 中验证对象形状的简单方法吗?
验证数据的方法有很多,我想说,任何您希望数据持久保存并匹配特定模型的系统,您都需要某种字段验证。 ORM 通常会这样做,但您也可以使用库,例如:
基本上,如果您想验证对象以确保它们适合特定的形状(模型/架构),您必须事先定义该形状。
import { z } from "zod";
// creating a schema for strings
const mySchema = z.string();
// parsing
mySchema.parse("tuna"); // => "tuna"
mySchema.parse(12); // => throws ZodError
您可以根据需要使其严格:
const mySchema = z.object({
id: z.number().positive(),
name: z.string().min(5).max(50),
description: z.string().min(5).max(500).optional(),
contact: z.object({
url: z.string().url(),
email: z.string().email(),
}),
})