Giter Site home page Giter Site logo

Comments (12)

joaogarin avatar joaogarin commented on June 19, 2024 2

Hello, Yes we do actually use a fork of this module for 4.x But we have some custom made code in there for our use case unfortunately we haven't yet been able to release it to its own module. that would be interesting though. I can put it in a repo to at least get that started. Will try to do that soon

from graphql-search-api.

darvanen avatar darvanen commented on June 19, 2024 1

we have some custom made code in there for our use case

Doesn't seem like something they'll be able to release.

This might help - I created a successful test query using the search API with just a couple of files, all in a custom module (im_base).

The query itself:

<?php

namespace Drupal\im_base\Plugin\GraphQL\DataProducer;

use Drupal\Core\Cache\RefinableCacheableDependencyInterface;
use Drupal\graphql\Plugin\GraphQL\DataProducer\DataProducerPluginBase;
use Drupal\im_base\Wrappers\SearchConnection;
use Drupal\search_api\Entity\Index;

/**
 * @DataProducer(
 *   id = "im_search_entities",
 *   name = @Translation("Search entities"),
 *   description = @Translation("Loads a list of entities via Search API."),
 *   produces = @ContextDefinition("any",
 *     label = @Translation("Search connection")
 *   ),
 *   consumes = {
 *     "entity_type" = @ContextDefinition("any",
 *       label = @Translation("Entity type"),
 *       required = FALSE,
 *     )
 *   }
 * )
 */
class SearchEntities extends DataProducerPluginBase {

  public function resolve(string $entity_type, RefinableCacheableDependencyInterface $metadata) {
    $query = Index::load('default')->query();
    $query->addCondition('search_api_datasource', 'entity:' . $entity_type)
      ->addCondition($entity_type . '_deleted', FALSE)
      ->execute();

    $metadata->mergeCacheMaxAge(-1);

    return new SearchConnection($query);
  }

}

The connection to extract results, similar to the example in the graphql module:

<?php

namespace Drupal\im_base\Wrappers;

use Drupal\search_api\Query\QueryInterface;
use GraphQL\Deferred;

class SearchConnection {

  /**
   * @var QueryInterface
   */
  protected $query;

  /**
   * QueryConnection constructor.
   *
   * @param
   */
  public function __construct(QueryInterface $query) {
    $this->query = $query;
  }

  /**
   * @return int
   */
  public function total() {
    return $this->query->getResults()->getResultCount();
  }

  /**
   * @return array|\GraphQL\Deferred
   */
  public function items() {
    $results = $this->query->getResults()->getResultItems();
    if (empty($results)) {
      return [];
    }

    $results = array_keys($results);
    preg_match('/(\w*)\//', $results[0], $matches);
    $type = $matches[1];
    $ids = [];
    foreach($results as $result) {
      preg_match('/\/([0-9]*)/', $result, $matches);
      $ids[] = $matches[1];
    }

    $buffer = \Drupal::service('im_base.buffer.entity');
    $callback = $buffer->add($type, $ids);
    return new Deferred(function () use ($callback) {
      return $callback();
    });
  }

}

and the Entity Buffer which we overrode in order to provide field-level access checks. You could just just the standard entity buffer instead though.

<?php

namespace Drupal\im_base\GraphQL\Buffers;

use Drupal\graphql\GraphQL\Buffers\EntityBuffer;

class ImEntityBuffer extends EntityBuffer {

  /**
   * {@inheritdoc}
   */
  public function resolveBufferArray(array $buffer) {
    $type = reset($buffer)['type'];
    $ids = array_map(function (\ArrayObject $item) {
      return (array) $item['id'];
    }, $buffer);

    $ids = call_user_func_array('array_merge', $ids);
    $ids = array_values(array_unique($ids));

    // Load the buffered entities.
    $entities = $this->entityTypeManager
      ->getStorage($type)
      ->loadMultiple($ids);

    return array_map(function ($item) use ($entities) {
      if (is_array($item['id'])) {
        return array_reduce($item['id'], function ($carry, $current) use ($entities) {

          // We overrode the parent class so we could add an access check here.
          if (!empty($entities[$current]) && $entities[$current]->access('view')) {
            array_push($carry, $entities[$current]);
          }

          return $carry;
        }, []);
      }

      return isset($entities[$item['id']]) ? $entities[$item['id']] : NULL;
    }, $buffer);
  }

}

You will of course need the usual schema or schema extension files to utilise these, and register your entity buffer as a service if you do use a custom one.

from graphql-search-api.

duartegarin avatar duartegarin commented on June 19, 2024

Yes it should. I know at least one dev that was using it.
Did you clear your caches?

from graphql-search-api.

blackbart420 avatar blackbart420 commented on June 19, 2024

@duartegarin yes I cleared caches and I rebuilt tracking info in the search index but "searchAPISearch" is not available in GraphiQL

from graphql-search-api.

duartegarin avatar duartegarin commented on June 19, 2024

@blackbart420 That's strange because that field would always be available even if you had no indexes. The field not being available almost looks like the module wasn't properly installed?

from graphql-search-api.

blackbart420 avatar blackbart420 commented on June 19, 2024

Hello @duartegarin ,
so, I uninstalled search API and graphQL.
Then I reinstalled everything but same result.

Then I tried on a new empty website, with the drupal module GraphQL ^3.0 and this time it worked.
Then I tried the same thing with GraphQL ^4.0 and it does not work.

So maybe graphql-search-api is not yet compatible with the graphql-4.x version ?

from graphql-search-api.

duartegarin avatar duartegarin commented on June 19, 2024

Hi @blackbart420 ,
Sorry apologies only now properly read that in your initial comment you mention 4.x.
Indeed this module is only compatible with 3.x as 4.x is a total rewrite of the GraphQL module.
@joaogarin I think you guys were working on a 4.x solution?

from graphql-search-api.

blackbart420 avatar blackbart420 commented on June 19, 2024

Hi @duartegarin, I understand, I will be waiting for the 4.x support :)

from graphql-search-api.

ndrake0027 avatar ndrake0027 commented on June 19, 2024

@joaogarin and follow-up to the above? Where you able to put the 4.x compatible version in a repo or sandbox?

from graphql-search-api.

duartegarin avatar duartegarin commented on June 19, 2024

@ndrake0027 I'm going to close this issue as we don't support 3.x (I've updated the docs accordingly).

I've reached out to the #graphql channel in drupal Slack to see if anyone has any input for you, I also suggest you reach out to the community there for some possible code examples.

Sorry I can't help more here but I don't use 4.x at the moment so limited knowledge there.

from graphql-search-api.

duartegarin avatar duartegarin commented on June 19, 2024

Oh there we go, awesome!

Thanks @darvanen !

from graphql-search-api.

blackbart420 avatar blackbart420 commented on June 19, 2024

Thanks @darvanen !

from graphql-search-api.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.