Skip to content

Cacheability metadata not bubbled up for computed fields in GraphQL responses #1414

Open

Description

@rafatwork

It looks like cacheability metadata for computed fields are not bubbled up in GraphQL responses.
This is a similar issue as https://www.drupal.org/node/3423720 (but then for GraphQL responses).

Activity

  1. klaasvw commented on Oct 3, 2024

    @klaasvw

    I had a similar problem, where I had a computed field that had to return a Url to another entity that was referencing the entity.

    In the end the solution was making sure that the graphql field producer plugins use addCacheableDependency on the FieldContext passed to the resolve method.

    In my case I had to use entity_reference as the field type for the computed field (instead of uri). Because we're using the graphql_compose module for the schema I used the field_entity_reference producer plugin. This adds the referencing entity as a cacheable dependency, thus making sure the cacheability metadata is bubbled up.

    Example from the SchemaExtension plugin:

    public function registerResolvers(ResolverRegistryInterface $registry): void {
     // ...
      $registry->addFieldResolver(
          $bundle->getTypeSdl(),
          'your_custom_field',
          $builder->compose(
            // Make sure the referenced entities are added to the
            // cacheability metadata.
            $builder->produce('field_entity_reference')
              ->map('entity', $builder->fromParent())
              ->map('field', $builder->fromValue('your_custom_field'))
              ->map('types', $builder->fromValue(['node'])),
            $builder->produce('seek')
              ->map('input', $builder->fromParent())
              ->map('position', $builder->fromValue(0)),
            $builder->produce('entity_url')
              ->map('entity', $builder->fromParent()),
            $builder->callback(fn (?Url $url) => $url ? $url->toString() : NULL)
          )
        );
      // ...
    }
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions