JSON:API now support configuring the API to show a count of the amount if resources in a list. The key of this count can be configured.
In the prior releases it was impossible to add a count to an overview of Resources since JSON:API has no public PHP API, however some contributed and custom modules were able to decorate the Drupal\jsonapi\ResourceType\ResourceType class. That approach meant overwriting methods and resulted in a difficult to maintain solution. For example, jsonapi_extras overrides the class in order to allow enabling a count.
The JSON:API ResourceTypeBuildEvent now has a new method: setCollectionSizeMemberName(string $name = NULL). Subscribers to that event can now enable the collection count and set the member name used as key in the meta data of the lists.
If you need the collection name in the ResourceTypeBuildEvent you can use the getCollectionSizeMemberName() method.
See Drupal\jsonapi_test_resource_type_building\EventSubscriber\ResourceTypeBuildEventSubscriber for an example of how to alias a resource type name.
Example output when using $event->setCollectionSizeMemberName('count').
{
"jsonapi": {...},
"data": [...],
"meta": {
"count": 22
},
"links": {...}
}
Example output when using $event->setCollectionSizeMemberName('my_count_variable').
{
"jsonapi": {...},
"data": [...],
"meta": {
"my_count_variable": 22
},
"links": {...}
}
Comments
How is this actually used from a user's perspective?
How do we actually get this when calling a request?
If I call, say,
/jsonapi/node/some_node_type, there is nocountproperty in themetaobject. Is there any option to add?Update:
I figured out I need to implement an event subscriber. However, it looks like
setCollectionSizeMemberNamehas not been implemented. See https://api.drupal.org/api/drupal/core%21modules%21jsonapi%21src%21Resou...Update 2:
Ah, so I just clued in that's it's a draft feature. Never mind then - here's hoping it's going to be in core soon!