在 API 平台上的自定义状态提供程序中添加自定义 http 标头的最佳方式

问题描述 投票:0回答:1

我在 API 平台上与 CustomStateProviders 合作,以这种方式装饰返回 DTO(“表示”),我喜欢它(隐藏一些字段,...)

我使用标准 ApiPlatform\Doctrine\Orm\State\CollectionProvider 进行过滤、分页……并返回 JSON 对象:

---切---

namespace App\State;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use ApiPlatform\Doctrine\Orm\State\CollectionProvider;
use Doctrine\Persistence\ManagerRegistry;
use App\Dto\ClientRepresentation;

class ClientCollectionProvider implements ProviderInterface
{
    private CollectionProvider $collectionProvider;
    public function __construct(CollectionProvider $collectionProvider)
    {
        $this->collectionProvider = $collectionProvider;
    }

    public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
    {
        $origResult = $this->collectionProvider->provide($operation, $uriVariables, $context);
        header("Pagination-Pages: ".$origResult->getLastPage());
        header("Pagination-Count: ".$origResult->getTotalItems());
        header("Pagination-Limit: ".$origResult->getItemsPerPage());
        return array_map(
            fn($client): ClientRepresentation => ClientRepresentation::fromClient($client),
            iterator_to_array($origResult->getIterator())
        );
    }

}

---切---

正如任何人都可以阅读的那样,我添加了标准的“标题”php 函数来返回总页数(“Pagination-Pages”)项目总数(“Pagination-Items”)和当前配置的每页最大项目数(“Pagination-Pages”)限制”)。

它有效。

但对我来说,看起来不太好。 有没有更好的方法在 API 平台上的 CustomStateProvider 中设置自定义标头?

https://github.com/api-platform/core/issues/1548<< To add EventSubscriberInterface as shown in norkunas answer at very top might work, but for me it is "similar bad" as my attempt by using the standard php header-function.

http-headers api-platform.com
1个回答
0
投票

有多种方法可以实现这一目标。

既然您正在使用 json-ld,我假设您也使用 Hydra。我建议通过装饰 api 平台的 Hydra 集合规范化器来添加“伪”Hydra 属性。在此装饰器中,您还可以注入集合提供程序来检索分页编号并将其添加到响应中。看 https://api-platform.com/docs/core/serialization/#decorating-a-serializer-and-adding-extra-data

如果您确实想坚持使用标头,您可以通过创建事件订阅者并订阅 kernel.response 事件来添加它们。您也可以在这里注入您的集合提供者。您可以从事件中获取响应并添加标头。请参阅https://api-platform.com/docs/core/events/

© www.soinside.com 2019 - 2024. All rights reserved.