Кэшируются GET-запросы к REST Resource Plugin

Главные вкладки

Аватар пользователя Shipovnix Shipovnix 3 июля 2020 в 9:19

Создал REST Resource Plugin. Шлю ему GET-запрос с параметрами:
_format=json&foo=bar
Получаю ответ, вроде бы всё нормально.
Убираю из параметров запроса foo=bar, шлю на сервер, но метод этот параметр все равно видит. Сбросишь кэш — перестаёт видеть.
И обратная ситуация: после сброса кэша шлю запрос без указанного параметра, обрабатывается как надо. Добавляю параметр в строку — метод упорно её не видит, пока не сбросишь кэш.

<?php
public function get() {
  
// You must to implement the logic of your REST Resource here.
  // Use current user after pass authentication to validate access.
  
if (!$this->currentUser->hasPermission('wgtapi request')) {
    throw new 
AccessDeniedHttpException('Access denied');
  }  
  
$query = \Drupal::request()->query;
  
$response = [];
  if (
$query->has('foo')) {
    
$response['result'] = 'true';
  } else {
    
$response['result'] = 'false';
  }
  return new 
ResourceResponse($response);
}
?>

Лучший ответ

Аватар пользователя marassa marassa 3 июля 2020 в 14:11
1

По идее вот это должно сработать более корректно:
$build['#cache']['contexts'][] = 'url.query_args';

Комментарии

Аватар пользователя marassa marassa 3 июля 2020 в 11:23
1

Разбирайтесь с cache contexts. Куда-то нужно вставить кэш-контекст "url.query_args:foo" или просто "url.query_args". А вот куда именно - спросонья не соображу Wink

Аватар пользователя Shipovnix Shipovnix 3 июля 2020 в 12:51

Вот что выдает консоль на drupal debug:cache:context

 Context ID               Label                                       Class path
 cookies                  HTTP cookies                                Drupal\Core\Cache\Context\CookiesCacheContext
 headers                  HTTP-заголовки                              Drupal\Core\Cache\Context\HeadersCacheContext
 ip                       IP-адрес                                    Drupal\Core\Cache\Context\IpCacheContext
 languages                Язык                                        Drupal\Core\Cache\Context\LanguagesCacheContext
 protocol_version         Версия протокола                            Drupal\Core\Cache\Context\ProtocolVersionCacheContext
 request_format           Формат запроса                              Drupal\Core\Cache\Context\RequestFormatCacheContext
 route                    Маршрут                                     Drupal\Core\Cache\Context\RouteCacheContext
 route.menu_active_trails Активный пункт в меню                       Drupal\Core\Cache\Context\MenuActiveTrailsCacheContext
 route.name               Название маршрута                           Drupal\Core\Cache\Context\RouteNameCacheContext
 session                  Сессия                                      Drupal\Core\Cache\Context\SessionCacheContext
 session.exists           Сессия существует                           Drupal\Core\Cache\Context\SessionExistsCacheContext
 theme                    Тема                                        Drupal\Core\Cache\Context\ThemeCacheContext
 timezone                 Часовой пояс                                Drupal\Core\Cache\Context\TimeZoneCacheContext
 url                      URL                                         Drupal\Core\Cache\Context\UrlCacheContext
 url.path                 Путь                                        Drupal\Core\Cache\Context\PathCacheContext
 url.path.is_front        Является главной страницей                  Drupal\Core\Cache\Context\IsFrontPathCacheContext
 url.path.parent          Родительский путь                           Drupal\Core\Cache\Context\PathParentCacheContext
 url.query_args           Аргументы запроса                           Drupal\Core\Cache\Context\QueryArgsCacheContext
 url.query_args.pagers    Постраничный навигатор                      Drupal\Core\Cache\Context\PagersCacheContext
 url.site                 Сайт                                        Drupal\Core\Cache\Context\SiteCacheContext
 user                     Пользователь                                Drupal\Core\Cache\Context\UserCacheContext
 user.is_super_user       Является супер-пользователем                Drupal\Core\Cache\Context\IsSuperUserCacheContext
 user.node_grants         Представление доступа на просмотр материала Drupal\node\Cache\NodeAccessGrantsCacheContext
 user.permissions         Права доступа для учётной записи            Drupal\Core\Cache\Context\AccountPermissionsCacheContext
 user.roles               Роли пользователя                           Drupal\Core\Cache\Context\UserRolesCacheContext
Аватар пользователя Shipovnix Shipovnix 3 июля 2020 в 13:54

В общем, помогла конструкция

<?php
$build 
= array(
  
'#cache' => array(
    
'max-age' => 0,
  ),
);
return (new 
ResourceResponse($response$respcode))->addCacheableDependency($build);
?>

Только не знаю, насколько это правильно — обнулять время жизни кэша в подобных случаях.