From a331bad3de7dbe078cfb757d5dabdfe9bdd5911a Mon Sep 17 00:00:00 2001 From: Matt Glaman <27012-mglaman@users.noreply.drupalcode.org> Date: Wed, 3 Apr 2024 12:17:32 +0000 Subject: [PATCH] Issue #3155966 by mglaman, pixelwhip: ResourceResponseFactory to return a CacheableResourceResponse if request is cacheable --- jsonapi_resources.info.yml | 2 +- src/Unstable/ResourceResponseFactory.php | 27 ++++++++++++------------ 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/jsonapi_resources.info.yml b/jsonapi_resources.info.yml index 9e50852..eac9600 100644 --- a/jsonapi_resources.info.yml +++ b/jsonapi_resources.info.yml @@ -1,6 +1,6 @@ name: 'JSON:API Resources' description: "This module let's you define custom resources at routes of your choice that use existing resource types." -core_version_requirement: ^8.8 || ^9 || ^10 +core_version_requirement: ^9.1 || ^10 type: module dependencies: - drupal:jsonapi diff --git a/src/Unstable/ResourceResponseFactory.php b/src/Unstable/ResourceResponseFactory.php index e4222f8..a5429fb 100644 --- a/src/Unstable/ResourceResponseFactory.php +++ b/src/Unstable/ResourceResponseFactory.php @@ -75,21 +75,20 @@ final class ResourceResponseFactory { $includes = $this->getIncludes($request, $data); - // \Drupal\jsonapi\ResourceResponse no longer implements - // CacheableResponseInterface in Drupal 9.1. - // Drupal\jsonapi\CacheableResourceResponse has ben added for cacheable - // responses. Keep compatibility with Drupal < 9.1. - // See https://www.drupal.org/node/3163310 $document = new JsonApiDocumentTopLevel($data, $includes, $links, $meta); - $response = class_exists('\Drupal\jsonapi\CacheableResourceResponse') ? - new CacheableResourceResponse($document, $response_code, $headers) : - new ResourceResponse($document, $response_code, $headers); - // Make sure that different sparse fieldsets are cached differently. - $cache_contexts[] = 'url.query_args:fields'; - // Make sure that different sets of includes are cached differently. - $cache_contexts[] = 'url.query_args:include'; - $cacheability = (new CacheableMetadata())->addCacheContexts($cache_contexts); - $response->addCacheableDependency($cacheability); + + if ($request->isMethodCacheable()) { + $response = new CacheableResourceResponse($document, $response_code, $headers); + // Make sure that different sparse fieldsets are cached differently. + $cache_contexts[] = 'url.query_args:fields'; + // Make sure that different sets of includes are cached differently. + $cache_contexts[] = 'url.query_args:include'; + $cacheability = (new CacheableMetadata())->addCacheContexts($cache_contexts); + $response->addCacheableDependency($cacheability); + } + else { + $response = new ResourceResponse($document, $response_code, $headers); + } return $response; } -- GitLab