hyva-themes/magento2-graphql-view-model

为Hyvä主题提供自定义GraphQL查询和突变的能力。

安装量: 1,076,172

依赖项: 1

建议者: 0

安全: 0

星星: 6

关注者: 4

分支: 2

开放问题: 0

类型:magento2-module

1.0.5 2023-03-13 17:01 UTC

This package is auto-updated.

Last update: 2024-09-13 20:17:31 UTC


README

Hyvä Themes

hyva-themes/magento2-graphql-view-model

Supported Magento Versions

本模块添加了一个GraphQL ViewModel,允许在输出渲染之前自定义GraphQL查询和突变。

兼容Magento 2.3.4及以上版本。

它做了什么?

它提供

  • \Hyva\GraphqlViewModel\ViewModel\GraphqlViewModel,可以通过视图模型注册访问(或通过Layout XML注入)。
  • \Hyva\GraphqlViewModel\Model\GraphqlQueryEditor,可以用来向GraphQL查询添加字段和参数。
  • 事件hyva_graphql_render_before_ + 查询标识符事件观察者接收到查询字符串,并可以使用GraphqlQueryEditor来操纵它

使用方法

.phtml模板中,要使查询可定制,请使用GraphqlViewModel::query()方法包装它们

<?= $gqlViewModel->query("product_list_query", "
products(filter: {} pageSize: 20) {
  items {
    {$type}_products {
        sku
        id
        small_image {
          url
        }
    }
  }
}", ['type' => $type])
?>

第一个参数是事件名称后缀。
第二个参数是查询或突变作为字符串。
第三个参数是可选的,如果指定,将合并到事件参数中。

在上面的例子中,完整的事件名称将是hyva_graphql_render_before_product_list_query

在事件观察者中操纵查询时,可以使用GraphqlQueryEditor

public function execute(Observer $event)
{
    $gqlEditor = new GraphqlQueryEditor(); // or use dependency injection
    
    $queryString = $event->getData('gql_container')->getData('query');
    $linkType  = $event->getData('type');
    $path  = ['products', 'items', ($linkType ? "{$linkType}_products" : 'products'), 'small_image'];
    
    // add a single field to a result object
    $queryString = $gqlEditor->addFieldIn($queryString, $path, 'url_webp');
    
    // add multiple fields to a result object
    $queryString = $gqlEditor->addFieldIn($queryString, ['products', 'items', 'products', 'image'], 'label url_webp');
    
    // add a query argument
    $queryString = $gqlEditor->addArgumentIn($queryString, ['products', 'filter', 'name'], 'match', 'Tank');
    $queryString = $gqlEditor->addArgumentIn($queryString, ['products'], 'pageSize', 2);
    
    // set updated query back on container
    $event->getData('gql_container')->setData('query', $queryString);
}

示例方法调用的结果

$gqlEditor->addFieldIn($queryString, ['products', 'items', 'products', 'small_image'], 'label url_webp')

这样,在查询中设置了指定路径的字段

products {
  items {
    products {
      small_image {
        label
        url_webp
      }
    }
  }
}

无论是addFieldIn还是addArgumentIn方法,都是幂等的,所以如果指定的值已存在于查询字符串中,它们不会被更改。

addArgumentIn方法可以用来向查询或突变添加新参数,或者覆盖现有参数的值。

有关包括内联片段的更多示例,请参阅\Hyva\GraphqlViewModel\Model\GraphqlQueryEditorTest类。

安装

  1. 通过composer安装
    composer config repositories.hyva-themes/magento2-graphql-view-model git git@github.com:hyva-themes/magento2-graphql-view-model.git
    composer require hyva-themes/magento2-graphql-view-model
    
  2. 启用模块
    bin/magento module:enable Hyva_GraphqlViewModel
    

配置

无需配置。

许可证

BSD-3-Clause许可证。有关更多信息,请参阅许可证文件