Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add CursorPaginator support #287

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 14 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,21 +176,28 @@ $model->first();
#### Pagination

Unfortunately, offset of how many records to skip does not make sense for DynamoDb.
Instead, provide the last result of the previous query as the starting point for the next query.
However, you can use the `paginate` function on the query builder to get a CursorPaginator, which will
handle passing the last evaluated key around:

**Examples:**
```PHP
$paginator = $model->paginate();
```

The paginator implements laravel's pagination interface, so it supports automatic link generation as usual.
It will also try to extract the cursor from the request parameters automatically, so if you use the rendered
pagination links or resource collections, pagination should be seamless!

See https://laravel.com/docs/11.x/pagination#cursor-pagination and
https://laravel.com/docs/11.x/pagination#cursor-paginator-instance-methods for details.

For query such as:
If you need to manage the last evaluated key manually, you can use the `after` and `afterKey` methods to provide
a model or the raw key respectively:

```php
$query = $model->where('count', 10)->limit(2);
$items = $query->all();
$last = $items->last();
```

Take the last item of this query result as the next "offset":

```php
$nextPage = $query->after($last)->limit(2)->all();
// or
$nextPage = $query->afterKey($items->lastKey())->limit(2)->all();
Expand Down
68 changes: 68 additions & 0 deletions src/DynamoDbCursorPaginator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?php

namespace Baopham\DynamoDb;

use BaoPham\DynamoDb\Facades\DynamoDb;
use Illuminate\Pagination\Cursor;

class DynamoDbCursorPaginator extends \Illuminate\Pagination\CursorPaginator
{
public function __construct($items, $perPage, $cursor = null, array $options = [], private $lastEvaluatedKey = null)
{
parent::__construct($items, $perPage, $cursor, $options);

// The base paginator sets the `hasMore` flag based on the existence of elements beyond the perPage-limit.
// We can instead just lean on DynamoDB to tell us, based on the returned lastEvaluatedKey.
$this->hasMore = (boolean) $lastEvaluatedKey;
}

/**
* Return a cursor to the previous page.
*
* Since DynamoDB cannot page back we just always return null.
*
* @return null
*/
public function previousCursor()
{
return null;
}

/**
* Return a cursor to the next page.
*
* This is largely cloning the base method but then just returning a cursor holding the `lastEvaluatedKey` instead.
*
* @return Cursor|null
*/
public function nextCursor()
{
if ((is_null($this->cursor) && ! $this->hasMore) ||
(! is_null($this->cursor) && $this->cursor->pointsToNextItems() && ! $this->hasMore)) {
return null;
}

if ($this->items->isEmpty()) {
return null;
}

// The Cursor implementation expects the parameters to only be 1 level deep, so we JSON-Encode the lastEvaluatedKey,
// since it can hold both a PK and an SK.
return new Cursor(['lastEvaluatedKey' => json_encode(DynamoDb::unmarshalItem($this->lastEvaluatedKey))]);
}

/**
* Get the instance as an array.
*
* We patch in the first_page_url here, since we can always just jump back to the first page by not passing a start
* key to the query.
*
* @return array|string[]
*/
public function toArray()
{
return array_merge(parent::toArray(), [
'first_page_url' => $this->url(null),
]);
}
}
31 changes: 31 additions & 0 deletions src/DynamoDbQueryBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,12 @@
use BaoPham\DynamoDb\Facades\DynamoDb;
use BaoPham\DynamoDb\H;
use Closure;
use Illuminate\Contracts\Pagination\CursorPaginator;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Pagination\Cursor;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Arr;

class DynamoDbQueryBuilder
Expand Down Expand Up @@ -444,6 +447,34 @@ public function chunk($chunkSize, callable $callback)
return true;
}

public function paginate($perPage = 15, $columns = [], $cursorName = 'cursor', $cursor = null): CursorPaginator
{
if (! $cursor instanceof Cursor) {
$cursor = is_string($cursor)
? Cursor::fromEncoded($cursor)
: DynamoDbCursorPaginator::resolveCurrentCursor($cursorName, $cursor);
}

$this->limit($perPage);

if ($cursor && $cursor->pointsToNextItems()) {
$this->afterKey(json_decode($cursor->parameter('lastEvaluatedKey')));
}

$items = $this->get($columns);

return new DynamoDbCursorPaginator(
$items,
$perPage,
$cursor,
[
'path' => Paginator::resolveCurrentPath(),
'cursorName' => $cursorName,
],
$this->lastEvaluatedKey,
);
}

/**
* @param $id
* @param array $columns
Expand Down
92 changes: 92 additions & 0 deletions tests/DynamoDbCursorPaginatorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
<?php namespace Baopham\Dynamodb\tests;

use Baopham\DynamoDb\DynamoDbCursorPaginator;
use Illuminate\Support\Str;

class DynamoDbCursorPaginatorTest extends DynamoDbModelTest
{

protected function getTestModel()
{
return new TestModel([]);
}

public function testCreatePaginator()
{
$paginator = TestModel::paginate();
$this->assertInstanceOf(DynamoDbCursorPaginator::class, $paginator);
}

public function testPageSizeLimit()
{
$this->seedMultiple(3);
$paginator = TestModel::paginate(1);

$this->assertCount(1, $paginator->items());
$this->assertTrue($paginator->hasMorePages());
}

public function testNextPage()
{
$this->seed(['id' => ['S' => 'ONE']]);
$this->seed(['id' => ['S' => 'TWO']]);
$this->seed(['id' => ['S' => 'THREE']]);

$paginator = TestModel::paginate(1);
$this->assertCount(1, $paginator->items());
$this->assertEquals('ONE', $paginator->items()[0]->id);
$this->assertTrue($paginator->hasMorePages());

$nextPaginator = TestModel::paginate(cursor: $paginator->nextCursor());

$items = $nextPaginator->items();
$this->assertCount(2, $items);
$this->assertEquals('TWO', $items[0]->id);
$this->assertFalse($nextPaginator->hasMorePages());
}

public function seed($attributes = [])
{
$item = [
'id' => ['S' => Str::random(36)],
'name' => ['S' => Str::random(36)],
'description' => ['S' => Str::random(256)],
'count' => ['N' => rand()],
'author' => ['S' => Str::random()],
];

$item = array_merge($item, $attributes);

$this->getClient()->putItem([
'TableName' => $this->testModel->getTable(),
'Item' => $item,
]);

return $item;
}
public function seedMultiple($amount = 1)
{
for ($i = 0; $i < $amount; $i++) {
$this->seed();
}
}
}

// phpcs:disable PSR1.Classes.ClassDeclaration.MultipleClasses
class TestModel extends \BaoPham\DynamoDb\DynamoDbModel
{
protected $fillable = ['name', 'description', 'count'];

protected $table = 'test_model';

protected $connection = 'test';

public $timestamps = true;

protected $dynamoDbIndexKeys = [
'count_index' => [
'hash' => 'count',
],
];
}
// phpcs:enable PSR1.Classes.ClassDeclaration.MultipleClasses
2 changes: 1 addition & 1 deletion tests/DynamoDbTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ protected function getEnvironmentSetUp($app)
'secret' => 'secret',
],
'region' => 'test',
'endpoint' => 'http://localhost:3000',
'endpoint' => env('DYNAMODB_LOCAL_ENDPOINT', 'http://localhost:3000'),
]);
}

Expand Down