请求验证器:验证 IRI [英] Request validator : validate an IRI

查看:32
本文介绍了请求验证器:验证 IRI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 api-plateform,到目前为止它一直是一个很棒的工具.我想在我的数据存储到我的数据库之前添加一些验证器.

I'm currently working with api-plateform which has been a great tool so far. I'd like to add some validator before my datas are stored into my database.

Api-platform 使用 IRI 而不是普通 id(即使您可以更改此行为).我想知道验证 IRI 的最佳方法是什么.

Api-platform works with IRI instead of plain id (even if you can change this behavior). I was wondering what would be the best way to validate an IRI.

假设我收到例如api/users/1".我想确保这个 IRI 实际上是有效的(即 id 存在于表user"中).

Let's say I receive for instance "api/users/1". I would like to make sure that this IRI is actually valid (i.e the id exists in the table "user").

我可以创建一个自定义验证器规则,它可以调用该 IRI 并查看它是否返回有效结果,或者甚至拆分字符串以获取 id 和表,然后进行 sql 查询以检查它是否不为空.

I could create a custom validator rule which would either call that IRI and see if it returns a valid result or even split the string to get the id and the table and then make an sql query to check if it's not null.

但我认为这两种解决方案都不是很理想.你对我有什么线索吗?

But I think both solutions are not really ideal. Do you have any clue for me ?

非常感谢!

推荐答案

API 平台会在反序列化过程中自动将 IRI 转换为引用实体的实例.

API Platform will automatically convert the IRI to an instance of the referenced entity during the deserialization process.

如果提供了无效的 IRI(格式错误或未找到),API 平台将自动抛出错误并返回 400(错误请求)HTTP 状态.

If an invalid IRI is provided (malformed, or not found), API Platform will automatically throw an error and return a 400 (Bad Request) HTTP status.

如果您想添加更高级的验证约束,您可以在根实体和相关实体(用户)上使用 Symfony 验证器.参见例如 @Valid 约束.

You can use the Symfony validator both on the root entity and on the related entity (the user) if you want to add more advanced validation constraints. See for instance the @Valid constraint.

这篇关于请求验证器:验证 IRI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆