Skip to content

Commit

Permalink
Refactor pagination logic in BaseQuery and QueryResponse classes
Browse files Browse the repository at this point in the history
  • Loading branch information
ewilan-riviere committed Feb 5, 2024
1 parent 2f541da commit 2e8fb9d
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 25 deletions.
20 changes: 1 addition & 19 deletions src/Queries/BaseQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -128,28 +128,10 @@ public function inertia(): QueryResponse
{
$this->loadRequest();

$response = QueryResponse::make(
return QueryResponse::make(
original: $this->paginate(),
defaultSort: $this->defaultSort
);
if ($this->noPaginate) {
$url = $this->request->url();
$perPage = count($response->data);

$response->current_page = 1;
$response->first_page_url = $url;
$response->from = 1;
$response->last_page = 1;
$response->last_page_url = $url;
$response->next_page_url = null;
$response->path = $url;
$response->per_page = $perPage;
$response->prev_page_url = null;
$response->to = $perPage;
$response->total = $perPage;
}

return $response;
}

/**
Expand Down
38 changes: 32 additions & 6 deletions src/Queries/QueryResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,23 +41,49 @@ public static function make(LengthAwarePaginator|Collection $original, string $d

$array = $original->toArray();

return new self(
$url = request()->url();
$items = $original->items();
$perPage = count($items);

$self = new self(
sort: request()->get('sort', $defaultSort),
filter: request()->get('filter'),
data: $original->items(),
data: $items,
current_page: $original->currentPage(),
first_page_url: $array['first_page_url'] ?? null,
from: $original->firstItem(),
first_page_url: $array['first_page_url'] ?? $url,
from: $original->firstItem() ?? 1,
last_page: $original->lastPage(),
last_page_url: $original->url($original->lastPage()),
links: QueryResponseLink::toArray($array['links'] ?? []),
next_page_url: $original->nextPageUrl(),
path: $original->path(),
path: $original->path() ?? $url,
per_page: $original->perPage(),
prev_page_url: $original->previousPageUrl(),
to: $original->lastItem(),
to: $original->lastItem() ?? $perPage,
total: $original->total(),
);

if (! $self->current_page) {
$self->current_page = 1;
}

if (! $self->last_page) {
$self->last_page = 1;
}

if (! $self->last_page_url) {
$self->last_page_url = $url;
}

if (! $self->per_page) {
$self->per_page = $perPage;
}

if (! $self->total) {
$self->total = $perPage;
}

return $self;
}
}

Expand Down

0 comments on commit 2e8fb9d

Please sign in to comment.