Can someone point me in right redirection how to cache POST responses also with this package? #356
Unanswered
iamprageeth
asked this question in
Q&A
Replies: 1 comment 2 replies
-
@iamprageeth I think you need to implement a cache profile and cache hasher. Here is an example: Hasher: <?php
namespace App\Support\Cache;
use Illuminate\Http\Request;
use Spatie\ResponseCache\CacheProfiles\CacheProfile;
use Spatie\ResponseCache\Hasher\RequestHasher;
class PostParamsAwareRequestHasher implements RequestHasher
{
protected CacheProfile $cacheProfile;
public function __construct(CacheProfile $cacheProfile)
{
$this->cacheProfile = $cacheProfile;
}
public function getHashFor(Request $request): string
{
$data = collect($request->all())->sortKeys()->toJson();
return md5("{$request->getRequestUri()}-{$data}/".$this->cacheProfile->useCacheNameSuffix($request));
}
} Profile: <?php
namespace App\Support\Cache;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Spatie\ResponseCache\CacheProfiles\BaseCacheProfile;
use Symfony\Component\HttpFoundation\Response;
class ApiRequestCacheProfile extends BaseCacheProfile
{
public function shouldCacheRequest(Request $request): bool
{
$cacheControl = $request->headers->get('Cache-Control', '');
if (Str::contains($cacheControl, ['no-store', 'no-cache'])) {
return false;
}
if ($this->isRunningInConsole()) {
return false;
}
return true;
}
public function shouldCacheResponse(Response $response): bool
{
if (!$this->hasCacheableResponseCode($response)) {
return false;
}
if (!$this->hasCacheableContentType($response)) {
return false;
}
return true;
}
public function hasCacheableResponseCode(Response $response): bool
{
if ($response->isSuccessful()) {
return true;
}
if ($response->isRedirection()) {
return true;
}
return false;
}
public function hasCacheableContentType(Response $response): bool
{
$contentType = $response->headers->get('Content-Type', '');
if (
Str::startsWith($contentType, 'text/') ||
Str::contains($contentType, ['/json', '+json'])
) {
return true;
}
return false;
}
} |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hi,
I know POST responses must not be cached. But this is a special scenario and the package documentation says it only caches GET Requests.
So Do we have to implement a custom cache profile for this ?
Thanks.
Beta Was this translation helpful? Give feedback.
All reactions