1

I created a few views which I use as JSON endpoints for a client application. However, they are not refreshed along with the content they serve.

What I have tried with no success:

  • Setting Caching to none (within the View page).
  • Disabled Views cache, (in Views' advanced settings).
  • Running drush cache-rebuild as a cronjob every 12h.

I know I can use a workaround like /api/my-endpoint?time=1234, but this is not an option for me, since I have no access to the consuming client's code anymore. Neither I plan to recreate all these endpoints in custom code.

How can I force a JSON view page not to be cached?

1

This is probably not related to caching inside of views, more likely on page level. You can disable page caching with the route option no_cache. Use a RouteSubscriber to alter the routes of views:

/src/Routing/RouteSubscriber.php

<?php

namespace Drupal\mymodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

class RouteSubscriber extends RouteSubscriberBase {

  protected function alterRoutes(RouteCollection $collection) {

    // no_cache for a specific view
    if ($route = $collection->get('view.testview.page_1')) {
      $route->setOption('no_cache', TRUE);
    }

    // or for all view displays of a specific type
    foreach ($collection->all() as $route) {
      if ($route->getOption('_view_display_plugin_id') == 'rest_export') {
        $route->setOption('no_cache', TRUE);
      }
    }

  }
}

mymodule.services.yml

services:
  mymodule.route_subscriber:
    class: Drupal\mymodule\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

This would not be necessary, if the view set the correct cache tags for the content it serves, so that the render cache could be invalidated if the content is changed.

  • This seems like a great idea. I'll give it a try on monday and keep you updated. Thanks. – typologist Mar 4 '17 at 19:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.