Search code examples
cachingdrupal-8json-api

How do I control the cacheability of a node rendered through JSON:API in Drupal 8/9?


We have a headless Drupal site that is exposing an API using JSON:API. One of the resources we're exposing is a content type that has a calculated/computed field inside that generates a time-limited link. The link is only valid for 120 seconds, but it seems that JSON:API wants to cache responses containing the field data for significantly longer.

Ideally, we don't want to completely turn off caching for these nodes, since they do get requested very frequently. Instead, we just want to limit caching to about 60 seconds. So, \Drupal::service('page_cache_kill_switch')->trigger() is not an ideal solution.

I've looked into altering the cache-ability of the response on the way out via an EventSubscriber on KernelEvents::RESPONSE but that only affects the top level of processing. As in, JSON:API caches all the pieces of the response (the "normalizations") separately, for maximum cache efficiency, so even though the response isn't served from cache, the JSON:API version of each node is.

I've also tried using service injection to wrap JSON:API's normalizers so that I can adjust the cache max age. It looks like I would need to do this at the field normalization level, but the JSON:API module discourages this by throwing a LogicException with an error of JSON:API does not allow adding more normalizers!.


Solution

  • So, after a lot of struggling with this, the solution is surprisingly simple -- instead of manipulating caching at the response level or the JSON:API level, manipulate it at the entity level!

    This worked:

    /**
     * Implements hook_ENTITY_TYPE_load() for nodes.
     */
    function my_module_node_load(array $entities) {
      foreach ($entities as $entity) {
        assert($entity instanceof NodeInterface);
    
        if ($entity->bundle() === 'my_content_type') {
          // Cache "my_content_type" entities for up to 60 seconds.
          $entity->addCacheableDependency(
            (new CacheableMetadata())->setCacheMaxAge(60)
          );
        }
      }
    }
    

    As a bonus, this uses core's normal caching mechanism; so, these nodes will only be cached for up to 60 secs even when being displayed on admin pages for us.