The #2942426: [DISCUSSION] Remove query counting and collection counts? explains that without a JSON:API Extras it's *almost* impossible to get a total number of items for a collection request within meta.count
. This caused by the "static" code of Drupal\jsonapi\ResourceType\ResourceType::includeCount()
:
public function includeCount() {
// By default, do not return counts in collection queries.
return FALSE;
}
Proposed resolution
- Add
string|null $totalCountMetaName
to theDrupal\jsonapi\ResourceType\ResourceType
. - Add
string|null $total_count_meta_name = NULL
as the argument toDrupal\jsonapi\ResourceType\ResourceType::__construct()
and assign it to$this->totalCountMetaName
. - Add logic to
Drupal\jsonapi\ResourceType\ResourceType::includeCount()
and return$this->totalCountMetaName !== NULL
, so the total count is included for collection responses if the meta name is provided. - Introduce
Drupal\jsonapi\ResourceType\ResourceType::getTotalCountMetaName(): ?string
that returns$this->totalCountMetaName
or'count'
if theDrupal\jsonapi\ResourceType\ResourceType::includeCount()
method is overridden. - In the
Drupal\jsonapi\Controller\EntityResource::respondWithCollection()
use$meta[$resource_type->getTotalCountMetaName()]
instead of$meta['count']
. - In the
Drupal\jsonapi\ResourceType\ResourceTypeBuildEvent
, introducestring|null $totalCountMetaName
,setTotalCountMetaName(?string $name): void
, andgetTotalCountMetaName(): ?string
that will allow changing the resource definition at a build time. - In the
Drupal\jsonapi\ResourceType\ResourceTypeRepository::createResourceType()
, query$event->getTotalCountMetaName()
for non-internal resource types and pass the value tonew ResourceType
.