Gib*_*hah 5 javascript validation shapes
我\xe2\x80\x99m想知道\xe2\x80\x99是否有一种简单的方法来验证Javascript中对象的形状。
\n\n现在,我有一个函数可以验证端点对象的形状,如下所示:
\n\nfunction validateEndpointShape(endpoint: any, hasId: boolean): boolean \n{\nreturn endpoint\n&& (hasId ? typeof endpoint.id === 'string' : true)\n&& typeof endpoint.name === 'string'\n&& typeof endpoint.description === 'string'\n&& typeof endpoint.url === 'string'\n&& GenericApiEndpointMethods[endpoint.method] !== undefined\n&& ApiEndpointTypes[endpoint.apiEndpointType] !== undefined\n&& endpoint.group\n&& typeof endpoint.group.groupPublicKey === 'string'\n&& typeof endpoint.group.groupName === 'string'\n&& typeof endpoint.reason === 'string'\n&& typeof endpoint.isPublic === 'boolean'\n&& typeof endpoint.isActive === 'boolean'\n&& authTypes[endpoint.authType] !== undefined\n&& Array.isArray(endpoint.parameters)\n&& Array.isArray(endpoint.headers);\n}\nRun Code Online (Sandbox Code Playgroud)\n\n这可能会变得麻烦且难以操作。我不想\xe2\x80\x99 不想为我创建的每个对象执行此操作。
\n\n当端点进入我们的云 Firebase 函数时,我们必须对其进行大量验证,以便我们知道何时拒绝不良数据。端点的形状是这些验证之一。
\n\n我尝试这样做:
\n\nDelete req.body.reason;\nreq.body[\xe2\x80\x98extraField\xe2\x80\x99] = \xe2\x80\x98xxx\xe2\x80\x99;\nConst endpoint: GenericApiEndpoint = req.body;\nconsole.log(\xe2\x80\x98endpoint =\xe2\x80\x98, endpoint);\nRun Code Online (Sandbox Code Playgroud)\n\n但 Javascript 并不关心\xe2\x80\x99。它将接受没有原因的端点(强制字段)和带有 extraField(模型中不存在的字段)的端点,并将其分配给类型为 GenericApiEndpoint 的对象。端点无故打印并带有额外字段。
\n\n我也尝试过:
\n\nConst endpoint = <GenericApiEndpoint>req.body;\nRun Code Online (Sandbox Code Playgroud)\n\n\xe2\x80\xa6但是Javascript也不\xe2\x80\x99关心这一点。
\n\n有人知道在 Javascript 中验证对象形状的简单方法吗?
\n有很多方法可以验证数据,我想说,任何您希望数据持久保存并匹配特定模型的系统,您都需要某种字段验证。ORM 通常会这样做,但您也可以使用库,例如:
基本上,底线是,如果您想验证对象以确保它们适合特定的形状(模型/模式),则必须事先定义该形状。
| 归档时间: |
|
| 查看次数: |
4722 次 |
| 最近记录: |