Api平台分页json格式

Yei*_*onM 5 symfony api-platform.com

我需要有关 json 格式的 api 平台分页的帮助。

这是我的 api_platform.yaml

api_platform:
    allow_plain_identifiers: true
    mapping:
        paths: ['%kernel.project_dir%/src/Entity']
    formats:
        json:     ['application/json']
Run Code Online (Sandbox Code Playgroud)

当我使用格式 hydra(默认)时,我得到了这样的东西

"hydra:view": {
    "@id": "/api/galleries?page=1",
    "@type": "hydra:PartialCollectionView",
    "hydra:first": "/api/galleries?page=1",
    "hydra:last": "/api/galleries?page=6",
    "hydra:next": "/api/galleries?page=2"
  }
Run Code Online (Sandbox Code Playgroud)

谁能帮我?如果有可能以 json 格式或其他方式使用 api 平台或 symfony 进行分页

谢谢你

was*_*ida 4

您应该创建一个事件订阅者:

<?php

namespace App\EventSubscriber;

use ApiPlatform\Core\EventListener\EventPriorities;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Paginator;

final class PaginateJsonSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::VIEW => ['normalizePagination', EventPriorities::PRE_RESPOND],
        ];
    }

    public function normalizePagination(
        ViewEvent $event
    ): void {
        $method = $event->getRequest()->getMethod();

        if ($method !== Request::METHOD_GET) {
            return;
        }

        if (($data = $event->getRequest()->attributes->get('data')) && $data instanceof Paginator) {
            $json = json_decode($event->getControllerResult(), true);
            $pagination = [
                'first' => 1,
                'current' => $data->getCurrentPage(),
                'last' => $data->getLastPage(),
                'previous' => $data->getCurrentPage() - 1 <= 0 ? 1 : $data->getCurrentPage() - 1,
                'next' => $data->getCurrentPage() + 1 > $data->getLastPage() ? $data->getLastPage() : $data->getCurrentPage() + 1,
                'totalItems' => $data->getTotalItems(),
                'parPage' => count($data)
            ];
            $res = [
                "data" => $json,
                "pagination" => $pagination
            ];
            $event->setControllerResult(json_encode($res));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)