Edits history of script submission #23756 for ' Create Product Variant (shopify)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Create Product Variant
     * Add a variant to an existing product. option_values maps each option name to its value (e.g. {"Size": "XL", "Color": "Red"}); a new value is added to the option automatically. If the product only has its "Default Title" variant, that variant is replaced. Set available with location_id to stock the variant at that location.
     */
    export async function main(
      auth: RT.Shopify,
      product_id: string,
      option_values: { [key: string]: 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,
      track_inventory: boolean | undefined,
      location_id: string | undefined,
      available: number | undefined
    ) {
      const productId = product_id.startsWith("gid://")
        ? product_id
        : `gid://shopify/Product/${product_id}`
      const locationId = location_id
        ? location_id.startsWith("gid://")
          ? location_id
          : `gid://shopify/Location/${location_id}`
        : undefined
    
      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!]!) { productVariantsBulkCreate(productId: $productId, variants: $variants) { productVariants { id legacyResourceId title sku price compareAtPrice inventoryQuantity selectedOptions { name value } barcodes(first: 5) { nodes { value type } } inventoryItem { id tracked measurement { weight { value unit } } } } userErrors { field message code } } }`,
            variables: {
              productId,
              variants: [
                {
                  optionValues: Object.entries(option_values).map(
                    ([optionName, name]) => ({ optionName, name })
                  ),
                  price: price || undefined,
                  compareAtPrice: compare_at_price || undefined,
                  barcodes: barcode ? [{ value: barcode }] : undefined,
                  inventoryItem: {
                    sku: sku || undefined,
                    tracked: track_inventory || available != null || undefined,
                    measurement:
                      weight != null
                        ? {
                            weight: {
                              value: weight,
                              unit: weight_unit || "KILOGRAMS",
                            },
                          }
                        : undefined,
                  },
                  inventoryQuantities:
                    locationId && available != null
                      ? [{ locationId, availableQuantity: available }]
                      : 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.productVariantsBulkCreate.userErrors.length) {
        throw new Error(JSON.stringify(data.productVariantsBulkCreate.userErrors))
      }
    
      return data.productVariantsBulkCreate
    }
    

    Submitted by hugo989 3 hours ago