0

I'm making an Ajax call to a route that performs an entityQuery. I know that when a node is added, it will change the results of that entityQuery, but until then, I want the route to return cached data so it doesn't have to perform the full query every time. What is the fastest way to do this?

Is there a way to put a cache tag on the route itself, that I can invalidate on node creation?

Should I do a $cache = \Drupal::cache()->get($cid) kind of thing in the route itself?

Thank you for reading.

  • 1
    Is this related to form api? If not, is REST API an option? This would probably do the caching you need by default. – 4k4 Aug 18 '16 at 14:53
  • If there is no reason to make a custom routing, REST API did provide the thing you want. – Jimmy Ko Aug 18 '16 at 15:16
4

What kind of ajax exactly? I guess it returns JSON?

Drupal's standard ajax API currently always does POST requests, those are not cached. So make sure you are doing a GET request.

Render caching is also only available for render arrays/HTML.

Your response would be cached if you return an object that returns CacheableResponseInterface but only by the (anoymous) internal page cache.

To have caching for all users, you likely need to implement your own logic to cache the response object as you suggested. By default, the node_list cache tag can be used to have it invalidated automatically whenever any node is created or saved. You can define your own cache tag (any string works) that you invalidate yourself only when certain conditions are true (for example, a new node of a specific type, matching your entity query).

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.