JavaScript中验证对象形状的简单方法

5

我想知道在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 的对象。端点将打印出 without reason 和 with extraField。

我还尝试过:

Const endpoint = <GenericApiEndpoint>req.body;

...但JavaScript也不在意这一点。

有人知道在JavaScript中验证对象形状的简单方法吗?


有很多验证数据的方法,如果您希望数据持久存在并符合特定模型,则需要某种类型的字段验证。ORM通常会执行此操作,但您也可以使用类似 https://validatejs.org 的库。顺便说一下,这看起来不像JavaScript。它是TypeScript吗? - Adam Gerthel
是的,这是TypeScript。但是在运行时需要验证形状。我会查看validatejs.org并回复您是否符合我的需求。谢谢。 - Gibran Shah
2个回答

2
有很多验证数据的方法,我认为在任何需要数据持久化和匹配特定模型的系统中,都需要某种字段验证。ORM通常会执行此操作,但您也可以使用以下库进行验证: 基本上,如果要验证对象以确保它们符合特定的形状(模型/模式),则必须事先定义该形状。"最初的回答"

有没有完全使用原生JS的解决方案? - Emidomenge
2
@Emidomenge 你如何定义原生JS?这些库是用JavaScript编写的。如果你想在不使用库的情况下实现相同的功能,基本上你需要编写与那些库相同的代码。 - Adam Gerthel
抱歉,我指的是一个自制的(最好是简单的)JavaScript函数。我不想使用库,因为它会增加捆绑包的大小。但最终,我别无选择。我使用它很容易上手。 - Emidomenge

0
使用Zod来验证您的数据
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(),
  }),
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接