Skip to content

Commit c1367dd

Browse files
JonPurvisSammyjo20
andauthored
Check Cache for Existing Data (#23)
* check for value in cache * add test * Empty Commit * Code fixes --------- Co-authored-by: Sammyjo20 <[email protected]>
1 parent cafeda3 commit c1367dd

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

src/Stores/LaravelCacheStore.php

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,17 @@ public function get(string $key): ?string
3232
*/
3333
public function set(string $key, string $value, int $ttl): bool
3434
{
35-
return $this->store->put($key, $value, $ttl);
35+
$result = $this->store->put($key, $value, $ttl);
36+
37+
// If the data already exists in the cache, then mysql returns 0 rows affected. Technically, this is not a
38+
// failure. We should check for this before returning anything and return true if it does exist.
39+
if ($result === false) {
40+
$existingValue = $this->store->get($key);
41+
if ($existingValue === $value) {
42+
return true;
43+
}
44+
}
45+
46+
return $result;
3647
}
3748
}

tests/Laravel/Feature/LaravelStoreTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use Saloon\RateLimitPlugin\Limit;
66
use Illuminate\Support\Facades\Cache;
7+
use Illuminate\Contracts\Cache\Repository;
78
use Saloon\RateLimitPlugin\Stores\LaravelCacheStore;
89

910
test('it records and can check exceeded limits', function () {
@@ -37,3 +38,17 @@
3738
'hits' => 1,
3839
]));
3940
});
41+
42+
test('it handles MySQL upsert behavior returning false for identical data', function () {
43+
$mockCache = Mockery::mock(Repository::class);
44+
45+
$key = 'test:limit';
46+
$value = json_encode(['timestamp' => time() + 60, 'hits' => 1]);
47+
48+
$mockCache->shouldReceive('put')->with($key, $value, Mockery::any())->andReturn(false);
49+
$mockCache->shouldReceive('get')->with($key)->andReturn($value);
50+
51+
$store = new LaravelCacheStore($mockCache);
52+
53+
expect($store->set($key, $value, 60))->toBeTrue();
54+
});

0 commit comments

Comments
 (0)