如何解决Symfony + API 平台:当 POST 数据具有意外例如,错误类型属性时,有没有办法抛出错误?
假设我有一个名为“Foo”且属性为“bar”的 API 资源,并且我使 POST 操作可用于创建一个新实例:
POST /api/foo
{
"bar": "whatever"
}
POST /api/foo
{
"bat": "whatever"
}
没有错误。
我可以在属性“bar”上添加一个 NotNull 约束,这样如果不包含“bar”,就会抛出一个错误,但是如果“bar”可以为空怎么办?现在的结果是“bar”变为 NULL,这不是最终用户所期望的。
或者,如果添加了任何其他属性,则不会抛出错误或警告,例如,如果“publish”不是属性但提交了以下内容:
POST /api/foo
{
"bar": "whatever","publish": true
}
没有关于意外“发布”属性的错误或警告。最终用户可能希望此属性可用,可能是因为它存在于其他资源上,但响应中没有错误。显然,最终用户应该阅读文档,但我更愿意直接在回复中提供反馈以确保 100% 合规。
总结: 如果我的 API 用户添加了错误的属性,或者不小心输入了属性名称,我该如何检测并抛出错误?
解决方法
您可以将@Groups 注释与 denormalization_context 一起使用。因此,您声明了被授予更新的属性。并使用强类型提示
<?php
declare(strict_types=1);
namespace AppBundle\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;
/**
* Class Foo
* @package AppBundle\Entity
* @ORM\Entity()
* @ORM\Table()
* @ApiResource(
* attributes={
* "normalization_context"={"groups"={"get"}},* "denormalization_context"={"groups"={"put,"post"}}
* },* itemOperations={},* collectionOperations={"post"}
* )
*/
class Foo
{
/**
* @var string
* @ORM\Column(name="bar",type="string",nullable=false)
* @Groups({"get","post"})
*/
private string $bar;
/**
* @var string
* @ORM\Column(name="bar",nullable=false)
* @Groups({"get"})
*/
private string $bat;
/**
* @var bool
* @ORM\Column(name="public",type="boolean",nullable=false)
* @Groups({"get","post"})
*/
private bool $public;
/**
* @return string
*/
public function getBar(): string
{
return $this->bar;
}
/**
* @param string $bar
*
* @return Foo
*/
public function setBar(string $bar): Foo
{
$this->bar = $bar;
return $this;
}
/**
* @return string
*/
public function getBat(): string
{
return $this->bat;
}
/**
* @param string $bat
*
* @return Foo
*/
public function setBat(string $bat): Foo
{
$this->bat = $bat;
return $this;
}
/**
* @return bool
*/
public function isPublic(): bool
{
return $this->public;
}
/**
* @param bool $public
*
* @return Foo
*/
public function setPublic(bool $public): Foo
{
$this->public = $public;
return $this;
}
}
您可以看到属性 $bat 没有组注释“post”:因此该字段在您的 POST 请求中未被授权。您也可以添加一些约束:例如:
use Symfony\Component\Validator\Constraint as Assert;
//...
/**
* @var string
* @ORM\Column(name="bar","post"})
* @Assert\NotBlank(message="property bar is mandatory")
*/
private string $bar;
希望能帮到你。
,我意识到这与非规范化步骤有关,并最终发现了这一点:
const Discord = require('discord.js');
const fs = require("fs");
const client = new Discord.Client();
const { prefix,token } = require("../config.json");
const cron = require("cron");
const test = require("./commands/autocode")(client);
test.start();
参考:https://github.com/api-platform/core/issues/1217#issuecomment-488662805
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。