首页 > 解决方案 > 如何使用 GraphQL 变异中的变量进行批量调整库存?

问题描述

我尝试批量调整我的 Shopify 产品变体的库存项目,如本文所述:https ://www.shopify.com/partners/blog/multi-location_and_graphql

我尝试在查询中对变体 ID 进行硬编码,效果很好:

<<-'GRAPHQL'
      mutation {
      inventoryBulkAdjustQuantityAtLocation(
        locationId: "gid://shopify/Location/5537988719",
        inventoryItemAdjustments: [
          {inventoryItemId: "gid://shopify/InventoryItem/21112836292719", availableDelta: 1},
          {inventoryItemId: "gid://shopify/InventoryItem/21112836325487", availableDelta: 10}
          ]) {
        inventoryLevels {
          available
        }
      }
    }
  GRAPHQL

现在我正在尝试将产品变体 ID 设置为如下变量:

require "graphql/client"
require "graphql/client/http"

class HomeController < ApplicationController
  API_KEY       = 'XXXXXX'.freeze
  PASSWORD      = 'XXXXXX'.freeze
  SHARED_SECRET = 'XXXXXX'.freeze
  SHOP_NAME     = 'xxxxxx'.freeze
  API_VERSION   = '2019-04'.freeze

  shop_url                      = "https://#{API_KEY}:#{PASSWORD}@#{SHOP_NAME}.myshopify.com/admin"
  ShopifyAPI::Base.site         = shop_url
  ShopifyAPI::Base.api_version  = API_VERSION
  CLIENT                        = ShopifyAPI::GraphQL.new

  BULK_ADJUST = CLIENT.parse <<-'GRAPHQL'
      mutation inventoryBulkAdjustQuantityAtLocation($inventoryItemAdjustments: [InventoryAdjustItemInput!]!, $locationId: ID!) {
        inventoryBulkAdjustQuantityAtLocation(inventoryItemAdjustments: $inventoryItemAdjustments, locationId: $locationId) {
          inventoryLevels {
            id
          }
          userErrors {
            field
            message
          }
        }
      }
  GRAPHQL

  def bulk_update_inventory
    inventoryItemAdjustments = [
        { "inventoryItemId" => "gid://shopify/InventoryItem/1234", "availableDelta" => 1 },
        { "inventoryItemId" => "gid://shopify/InventoryItem/5678", "availableDelta" => 10 }
    ]

    variables = {
        "inventoryItemAdjustments" => inventoryItemAdjustments,
        "locationId" => "gid://shopify/Location/9012"
    }

      result = CLIENT.query(BULK_ADJUST,
                          variables: variables)
    render :json => { :result => result }
  end

end

当我尝试运行查询时,出现以下错误:

Unknown action

The action 'bulk_update_inventory' could not be found for HomeController

有谁知道我为什么会出现这个错误?

标签: ruby-on-railsrubygraphqlshopify

解决方案


终于得到答案了!正确的查询是:

BULK_ADJUST = CLIENT.parse <<-'GRAPHQL'
      mutation($inventoryItemAdjustments: [InventoryAdjustItemInput!]!, $locationId: ID!) {
        inventoryBulkAdjustQuantityAtLocation(inventoryItemAdjustments: $inventoryItemAdjustments, locationId: $locationId) {
          inventoryLevels {
            id
          }
          userErrors {
            field
            message
          }
        }
      }
  GRAPHQL

必须删除“mutation”关键字后的“inventoryBulkAdjustQuantityAtLocation”一词。


推荐阅读