写一段 resolver 代码实现基于 SKU 列表的多仓库库存批量查询。

解读

在国内 Magento 2 面试中,GraphQL 是必考的 API 扩展方式。面试官想通过“多仓库 + 批量 SKU”这一真实业务场景,验证候选人是否掌握:

  1. GraphQL resolver 的注册与依赖注入
  2. 多源库存(MSI)表结构(inventory_source_item、inventory_source_stock_link)
  3. 批量查询的 SQL 优化(避免 N+1)
  4. 结果聚合与类型约束(严格返回可销售库存,而非物理库存)

题目隐含要求:返回结构必须包含 warehouse_code、sku、qty、is_in_stock,且支持分页与缓存标签,否则直接视为不合格。

知识点

  • Magento_InventoryApi:SourceItemRepositoryInterface、GetSourceItemsBySkuInterface
  • GraphQL schema 声明:@resolver 语法、type 定义、分页参数(currentPage、pageSize)
  • Service Contract 优先:禁止直接写 SQL,需用 SearchCriteriaBuilder 做 in-filter
  • 缓存策略:@cache 标签 cacheable="true" 与 cacheIdentity(Magento\GraphQl\Model\Query\ContextExt)
  • 性能:join 库存索引表(inventory_stock_1)+ 使用 getConnection()->fetchAssoc() 一次性拉取
  • 异常处理:sku 不存在时返回空节点,不抛 404,符合 GraphQL 部分错误规范

答案

  1. 声明 schema(etc/schema.graphqls)
type Query {
    multiWarehouseStock(
        skus: [String!]! @doc(description: "商品 SKU 列表")
        currentPage: Int = 1
        pageSize: Int = 20
    ): WarehouseStockOutput @resolver(class: "Vendor\\InventoryGraphQl\\Model\\Resolver\\MultiWarehouseStock") @cache(cacheable: true)
}

type WarehouseStockOutput {
    items: [WarehouseStockItem!]!
    total_count: Int!
}

type WarehouseStockItem {
    warehouse_code: String!
    sku: String!
    qty: Float!
    is_in_stock: Boolean!
}
  1. Resolver 实现(Vendor/InventoryGraphQl/Model/Resolver/MultiWarehouseStock.php)
<?php
declare(strict_types=1);

namespace Vendor\InventoryGraphQl\Model\Resolver;

use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\InventoryApi\Api\GetSourceItemsBySkuInterface;
use Magento\InventoryApi\Api\Data\SourceItemInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\App\ResourceConnection;

class MultiWarehouseStock implements ResolverInterface
{
    private GetSourceItemsBySkuInterface $getSourceItemsBySku;
    private SearchCriteriaBuilder $searchCriteriaBuilder;
    private ResourceConnection $resource;

    public function __construct(
        GetSourceItemsBySkuInterface $getSourceItemsBySku,
        SearchCriteriaBuilder $searchCriteriaBuilder,
        ResourceConnection $resource
    ) {
        $this->getSourceItemsBySku = $getSourceItemsBySku;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->resource = $resource;
    }

    public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
    {
        $skus = array_unique($args['skus']);
        $currentPage = (int)($args['currentPage'] ?? 1);
        $pageSize = (int)($args['pageSize'] ?? 20);

        // 1. 一次性查询所有 SKU 的源库存
        $searchCriteria = $this->searchCriteriaBuilder
            ->addFilter(SourceItemInterface::SKU, $skus, 'in')
            ->create();
        $sourceItems = $this->getSourceItemsBySku->execute($searchCriteria);

        // 2. 聚合结果
        $output = [];
        foreach ($sourceItems->getItems() as $item) {
            $output[] = [
                'warehouse_code' => $item->getSourceCode(),
                'sku' => $item->getSku(),
                'qty' => (float)$item->getQuantity(),
                'is_in_stock' => (bool)$item->getStatus()
            ];
        }

        // 3. 手动分页(GraphQL 层)
        $total = count($output);
        $offset = ($currentPage - 1) * $pageSize;
        $items = array_slice($output, $offset, $pageSize);

        return [
            'items' => $items,
            'total_count' => $total
        ];
    }
}
  1. 缓存身份(可选,但加分)
public function getIdentities(array $resolvedData): array
{
    $tags = [];
    foreach ($resolvedData['items'] as $item) {
        $tags[] = 'catalog_product_' . $item['sku'];
    }
    return array_unique($tags);
}

拓展思考

  • 高并发场景:若 SKU 数量 >5k,建议把 resolver 拆成 DataProvider + 异步队列,利用 Redis 缓存仓库库存快照,TTL 设为 30s,降低 MySQL 压力。
  • 跨源可用库存:国内仓、保税仓、海外仓的“可销售库存”需减去未发订单占用量,可引入 Magento_InventoryReservation 模块的 GetReservationsQuantityInterface 做实时扣减。
  • 安全合规:仓库代码属于内部数据,需加 ACL(Magento_Backend::inventory_sources),在 resolver 里注入 AuthorizationInterface,无权限用户返回空列表,避免信息泄露。
  • PWA 体验:前端往往要求“就近仓库”优先,可在 resolver 增加 geocode 参数,通过 阿里云物流 GEO API 计算最短配送时效,返回排序后的仓库列表,体现业务深度。

掌握以上细节,即可在国内一线电商公司的 Magento 技术面试中拿到高分。