handle sparse fieldsets (?fields=)

This commit is contained in:
Andrei V. Goryunov 2022-09-19 12:41:08 +03:00
parent de4dacd1da
commit 324d72bd6e
5 changed files with 27 additions and 0 deletions

View File

@ -57,6 +57,13 @@ interface AdapterInterface
*/ */
public function filterByExpression($query, string $expression): void; public function filterByExpression($query, string $expression): void;
/**
* Manipulate the query to only include specific fields.
*
* @param string|array $fields Comma-separated list of field names to include or array of such lists for every resource type
*/
public function sparseFieldset($query, $fields): void;
/** /**
* Manipulate the query to sort by the given attribute in the given direction. * Manipulate the query to sort by the given attribute in the given direction.
*/ */

View File

@ -65,6 +65,10 @@ class EloquentAdapter implements AdapterInterface
{ {
} }
public function sparseFieldset($query, $fields): void
{
}
public function sortByAttribute($query, Attribute $attribute, string $direction): void public function sortByAttribute($query, Attribute $attribute, string $direction): void
{ {
$query->orderBy($this->getAttributeProperty($attribute), $direction); $query->orderBy($this->getAttributeProperty($attribute), $direction);

View File

@ -31,6 +31,10 @@ class NullAdapter implements AdapterInterface
{ {
} }
public function sparseFieldset($query, $fields): void
{
}
public function sortByAttribute($query, Attribute $attribute, string $direction): void public function sortByAttribute($query, Attribute $attribute, string $direction): void
{ {
} }

View File

@ -65,6 +65,10 @@ class Index
$resourceType->applyFilters($query, $filter, $context); $resourceType->applyFilters($query, $filter, $context);
} }
if ($fields = $context->getRequest()->getQueryParams()['fields'] ?? null) {
$resourceType->applySparseFieldset($query, $fields, $context);
}
run_callbacks($schema->getListeners('listing'), [$query, $context]); run_callbacks($schema->getListeners('listing'), [$query, $context]);
$total = $schema->isCountable() ? $adapter->count($query) : null; $total = $schema->isCountable() ? $adapter->count($query) : null;

View File

@ -169,6 +169,14 @@ final class ResourceType
} }
} }
/**
* Apply the resource type's sparse fieldsets to a query.
*/
public function applySparseFieldset($query, $fields, Context $context): void
{
$this->adapter->sparseFieldset($query, $fields);
}
private function filterByAttribute($query, Attribute $attribute, $value): void private function filterByAttribute($query, Attribute $attribute, $value): void
{ {
if (preg_match('/(.+)\.\.(.+)/', $value, $matches)) { if (preg_match('/(.+)\.\.(.+)/', $value, $matches)) {