Edits history of script submission #23767 for ' Update Product Variant (shopify)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Update Product Variant
     * Update a variant's price, compare-at price, SKU, barcode, weight or option values. Only the fields you fill in are changed. option_values maps option names to new values (e.g. {"Size": "XL"}).
     */
    export async function main(
      auth: RT.Shopify,
      product_id: string,
      variant_id: string,
      price: string | undefined,
      compare_at_price: string | undefined,
      sku: string | undefined,
      barcode: string | undefined,
      weight: number | undefined,
      weight_unit: "KILOGRAMS" | "GRAMS" | "POUNDS" | "OUNCES" | undefined,
      inventory_policy: "DENY" | "CONTINUE" | undefined,
      option_values: { [key: string]: string } | undefined
    ) {
      const productId = product_id.startsWith("gid://")
        ? product_id
        : `gid://shopify/Product/${product_id}`
      const id = variant_id.startsWith("gid://")
        ? variant_id
        : `gid://shopify/ProductVariant/${variant_id}`
      const inventoryItem = {
        sku: sku || undefined,
        measurement:
          weight != null
            ? { weight: { value: weight, unit: weight_unit || "KILOGRAMS" } }
            : undefined,
      }
      const options = Object.entries(option_values ?? {})
    
      const response = await fetch(
        `https://${auth.store_name}.myshopify.com/admin/api/2026-10/graphql.json`,
        {
          method: "POST",
          headers: {
            "X-Shopify-Access-Token": auth.token,
            "Content-Type": "application/json",
            Accept: "application/json",
          },
          body: JSON.stringify({
            query: `mutation ($productId: ID!, $variants: [ProductVariantsBulkInput!]!) { productVariantsBulkUpdate(productId: $productId, variants: $variants) { productVariants { id legacyResourceId title sku price compareAtPrice inventoryPolicy updatedAt selectedOptions { name value } barcodes(first: 5) { nodes { value type } } inventoryItem { id measurement { weight { value unit } } } } userErrors { field message code } } }`,
            variables: {
              productId,
              variants: [
                {
                  id,
                  price: price || undefined,
                  compareAtPrice: compare_at_price || undefined,
                  barcodes: barcode ? [{ value: barcode }] : undefined,
                  inventoryPolicy: inventory_policy || undefined,
                  inventoryItem:
                    inventoryItem.sku || inventoryItem.measurement
                      ? inventoryItem
                      : undefined,
                  optionValues: options.length
                    ? options.map(([optionName, name]) => ({ optionName, name }))
                    : undefined,
                },
              ],
            },
          }),
        }
      )
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      const { data, errors } = await response.json()
      if (errors) {
        throw new Error(JSON.stringify(errors))
      }
      if (data.productVariantsBulkUpdate.userErrors.length) {
        throw new Error(JSON.stringify(data.productVariantsBulkUpdate.userErrors))
      }
    
      return data.productVariantsBulkUpdate
    }
    

    Submitted by hugo989 3 hours ago