Drupal Answers Asked by user1648228 on February 2, 2021
I’m using Drupal 8 in headless mode with Angular 8 as my client, but Drupal caches the API calls. For example, I have an end point which suppose to give items in random order, but this doesn’t happen. I only get cache items in a particular order.
How can I overcome this? I have tried to disable the cache modules, but I still get the same behavior.
I prefer to disable cache entirely for my endpoints. You can do it adding a cacheable dependency with a zero MaxAge to the ResourceResponse object.
Here is an example:
$response = new ResourceResponse($data);
$disable_cache = new CacheableMetadata();
$disable_cache->setCacheMaxAge(0);
$response->addCacheableDependency($disable_cache);
return $response;
Answered by Juanmi Sosso on February 2, 2021
There are two level of caching in Drupal.
1.) Dynamic Page Cache
You have to provide the correct cache metadata on the json response.
For example use the cache properties from a config or content entity
$response->addCacheableDependency($entitiy);
or build a cacheable metadata object and add this to the response:
$build = [
'#cache' => [
'contexts' => ['url.query_args'],
'tags' => ['node:1', 'node_list'],
'max-age' => 300,
],
];
$cache_metadata = DrupalCoreCacheCacheableMetadata::createFromRenderArray($build);
$response->addCacheableDependency($cache_metadata);
You can use this in a custom controller or implement this in an event subscriber to alter responses from other modules (core or contrib).
2.) Internal Page Cache
The module Internal Page Cache caches all responses for anonymous requests regardless of the cache metadata. You can uninstall this module to disable this cache.
Alternative solution
On the client side append a different query string on every request to get a fresh response:
node/123?_format=json&time=123456789
This will disable the Internal Page Cache and parts of the Dynamic Page Cache.
Reference: https://www.drupal.org/docs/8/core/modules/rest/javascript-and-drupal-8-restful-web-services
Answered by 4k4 on February 2, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP